Coverage Report

Created: 2023-07-18 01:59

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.89.7
2
// (main code and documentation)
3
4
// Help:
5
// - Read FAQ at http://dearimgui.com/faq
6
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
7
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
8
// Read imgui.cpp for details, links and comments.
9
10
// Resources:
11
// - FAQ                   http://dearimgui.com/faq
12
// - Homepage              https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/6478 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Getting Started       https://github.com/ocornut/imgui/wiki/Getting-Started
17
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
18
// - Issues & support      https://github.com/ocornut/imgui/issues
19
20
// Getting Started?
21
// - Read https://github.com/ocornut/imgui/wiki/Getting-Started
22
// - For first-time users having issues compiling/linking/running/loading fonts:
23
//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
24
25
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
26
// See LICENSE.txt for copyright and licensing details (standard MIT License).
27
// This library is free but needs your support to sustain development and maintenance.
28
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
29
// Individuals: you can support continued development via donations. See docs/README or web page.
30
31
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
32
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
33
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
34
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
35
// to a better solution or official support for them.
36
37
/*
38
39
Index of this file:
40
41
DOCUMENTATION
42
43
- MISSION STATEMENT
44
- CONTROLS GUIDE
45
- PROGRAMMER GUIDE
46
  - READ FIRST
47
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
48
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
49
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
50
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
51
- API BREAKING CHANGES (read me when you update!)
52
- FREQUENTLY ASKED QUESTIONS (FAQ)
53
  - Read all answers online: https://www.dearimgui.com/faq, or in docs/FAQ.md (with a Markdown viewer)
54
55
CODE
56
(search for "[SECTION]" in the code to find them)
57
58
// [SECTION] INCLUDES
59
// [SECTION] FORWARD DECLARATIONS
60
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
61
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
62
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
63
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
64
// [SECTION] MISC HELPERS/UTILITIES (File functions)
65
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
66
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
67
// [SECTION] ImGuiStorage
68
// [SECTION] ImGuiTextFilter
69
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
70
// [SECTION] ImGuiListClipper
71
// [SECTION] STYLING
72
// [SECTION] RENDER HELPERS
73
// [SECTION] INITIALIZATION, SHUTDOWN
74
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
75
// [SECTION] INPUTS
76
// [SECTION] ERROR CHECKING
77
// [SECTION] LAYOUT
78
// [SECTION] SCROLLING
79
// [SECTION] TOOLTIPS
80
// [SECTION] POPUPS
81
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
82
// [SECTION] DRAG AND DROP
83
// [SECTION] LOGGING/CAPTURING
84
// [SECTION] SETTINGS
85
// [SECTION] LOCALIZATION
86
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
87
// [SECTION] DOCKING
88
// [SECTION] PLATFORM DEPENDENT HELPERS
89
// [SECTION] METRICS/DEBUGGER WINDOW
90
// [SECTION] DEBUG LOG WINDOW
91
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
92
93
*/
94
95
//-----------------------------------------------------------------------------
96
// DOCUMENTATION
97
//-----------------------------------------------------------------------------
98
99
/*
100
101
 MISSION STATEMENT
102
 =================
103
104
 - Easy to use to create code-driven and data-driven tools.
105
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
106
 - Easy to hack and improve.
107
 - Minimize setup and maintenance.
108
 - Minimize state storage on user side.
109
 - Minimize state synchronization.
110
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
111
 - Efficient runtime and memory consumption.
112
113
 Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
114
115
 - Doesn't look fancy, doesn't animate.
116
 - Limited layout features, intricate layouts are typically crafted in code.
117
118
119
 CONTROLS GUIDE
120
 ==============
121
122
 - MOUSE CONTROLS
123
   - Mouse wheel:                   Scroll vertically.
124
   - SHIFT+Mouse wheel:             Scroll horizontally.
125
   - Click [X]:                     Close a window, available when 'bool* p_open' is passed to ImGui::Begin().
126
   - Click ^, Double-Click title:   Collapse window.
127
   - Drag on corner/border:         Resize window (double-click to auto fit window to its contents).
128
   - Drag on any empty space:       Move window (unless io.ConfigWindowsMoveFromTitleBarOnly = true).
129
   - Left-click outside popup:      Close popup stack (right-click over underlying popup: Partially close popup stack).
130
131
 - TEXT EDITOR
132
   - Hold SHIFT or Drag Mouse:      Select text.
133
   - CTRL+Left/Right:               Word jump.
134
   - CTRL+Shift+Left/Right:         Select words.
135
   - CTRL+A or Double-Click:        Select All.
136
   - CTRL+X, CTRL+C, CTRL+V:        Use OS clipboard.
137
   - CTRL+Z, CTRL+Y:                Undo, Redo.
138
   - ESCAPE:                        Revert text to its original value.
139
   - On OSX, controls are automatically adjusted to match standard OSX text editing shortcuts and behaviors.
140
141
 - KEYBOARD CONTROLS
142
   - Basic:
143
     - Tab, SHIFT+Tab               Cycle through text editable fields.
144
     - CTRL+Tab, CTRL+Shift+Tab     Cycle through windows.
145
     - CTRL+Click                   Input text into a Slider or Drag widget.
146
   - Extended features with `io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard`:
147
     - Tab, SHIFT+Tab:              Cycle through every items.
148
     - Arrow keys                   Move through items using directional navigation. Tweak value.
149
     - Arrow keys + Alt, Shift      Tweak slower, tweak faster (when using arrow keys).
150
     - Enter                        Activate item (prefer text input when possible).
151
     - Space                        Activate item (prefer tweaking with arrows when possible).
152
     - Escape                       Deactivate item, leave child window, close popup.
153
     - Page Up, Page Down           Previous page, next page.
154
     - Home, End                    Scroll to top, scroll to bottom.
155
     - Alt                          Toggle between scrolling layer and menu layer.
156
     - CTRL+Tab then Ctrl+Arrows    Move window. Hold SHIFT to resize instead of moving.
157
   - Output when ImGuiConfigFlags_NavEnableKeyboard set,
158
     - io.WantCaptureKeyboard flag is set when keyboard is claimed.
159
     - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
160
     - io.NavVisible: true when the navigation cursor is visible (usually goes to back false when mouse is used).
161
162
 - GAMEPAD CONTROLS
163
   - Enable with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
164
   - Particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
165
   - Download controller mapping PNG/PSD at http://dearimgui.com/controls_sheets
166
   - Backend support: backend needs to:
167
      - Set 'io.BackendFlags |= ImGuiBackendFlags_HasGamepad' + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
168
      - For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
169
        Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
170
      - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
171
   - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
172
     with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
173
174
 - REMOTE INPUTS SHARING & MOUSE EMULATION
175
   - PS4/PS5 users: Consider emulating a mouse cursor with DualShock touch pad or a spare analog stick as a mouse-emulation fallback.
176
   - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + run examples/libs/synergy/uSynergy.c (on your console/tablet/phone app)
177
     in order to share your PC mouse/keyboard.
178
   - See https://github.com/ocornut/imgui/wiki/Useful-Extensions#remoting for other remoting solutions.
179
   - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
180
     Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs Dear ImGui to move your mouse cursor along with navigation movements.
181
     When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
182
     When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
183
     (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, Dear ImGui will misbehave as it will see your mouse moving back & forth!)
184
     (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
185
     to set a boolean to ignore your other external mouse positions until the external source is moved again.)
186
187
188
 PROGRAMMER GUIDE
189
 ================
190
191
 READ FIRST
192
 ----------
193
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
194
 - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
195
   destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
196
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
197
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
198
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
199
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
200
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
201
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
202
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
203
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
204
 - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
205
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
206
   If you get an assert, read the messages and comments around the assert.
207
 - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
208
 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
209
   See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
210
   However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
211
 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
212
213
214
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
215
 ----------------------------------------------
216
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
217
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
218
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
219
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
220
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
221
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
222
   likely be a comment about it. Please report any issue to the GitHub page!
223
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
224
 - Try to keep your copy of Dear ImGui reasonably up to date.
225
226
227
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
228
 ---------------------------------------------------------------
229
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
230
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
231
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
232
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
233
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
234
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
235
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
236
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
237
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
238
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
239
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
240
241
242
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
243
 --------------------------------------
244
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
245
 The sub-folders in examples/ contain examples applications following this structure.
246
247
     // Application init: create a dear imgui context, setup some options, load fonts
248
     ImGui::CreateContext();
249
     ImGuiIO& io = ImGui::GetIO();
250
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
251
     // TODO: Fill optional fields of the io structure later.
252
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
253
254
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
255
     ImGui_ImplWin32_Init(hwnd);
256
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
257
258
     // Application main loop
259
     while (true)
260
     {
261
         // Feed inputs to dear imgui, start new frame
262
         ImGui_ImplDX11_NewFrame();
263
         ImGui_ImplWin32_NewFrame();
264
         ImGui::NewFrame();
265
266
         // Any application code here
267
         ImGui::Text("Hello, world!");
268
269
         // Render dear imgui into screen
270
         ImGui::Render();
271
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
272
         g_pSwapChain->Present(1, 0);
273
     }
274
275
     // Shutdown
276
     ImGui_ImplDX11_Shutdown();
277
     ImGui_ImplWin32_Shutdown();
278
     ImGui::DestroyContext();
279
280
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
281
282
     // Application init: create a dear imgui context, setup some options, load fonts
283
     ImGui::CreateContext();
284
     ImGuiIO& io = ImGui::GetIO();
285
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
286
     // TODO: Fill optional fields of the io structure later.
287
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
288
289
     // Build and load the texture atlas into a texture
290
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
291
     int width, height;
292
     unsigned char* pixels = nullptr;
293
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
294
295
     // At this point you've got the texture data and you need to upload that to your graphic system:
296
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
297
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
298
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
299
     io.Fonts->SetTexID((void*)texture);
300
301
     // Application main loop
302
     while (true)
303
     {
304
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
305
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
306
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
307
        io.DisplaySize.x = 1920.0f;             // set the current display width
308
        io.DisplaySize.y = 1280.0f;             // set the current display height here
309
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
310
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
311
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
312
313
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
314
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
315
        ImGui::NewFrame();
316
317
        // Most of your application code here
318
        ImGui::Text("Hello, world!");
319
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
320
        MyGameRender(); // may use any Dear ImGui functions as well!
321
322
        // Render dear imgui, swap buffers
323
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
324
        ImGui::EndFrame();
325
        ImGui::Render();
326
        ImDrawData* draw_data = ImGui::GetDrawData();
327
        MyImGuiRenderFunction(draw_data);
328
        SwapBuffers();
329
     }
330
331
     // Shutdown
332
     ImGui::DestroyContext();
333
334
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
335
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
336
 Please read the FAQ and example applications for details about this!
337
338
339
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
340
 ---------------------------------------------
341
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
342
343
    void MyImGuiRenderFunction(ImDrawData* draw_data)
344
    {
345
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
346
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
347
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
348
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
349
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
350
       ImVec2 clip_off = draw_data->DisplayPos;
351
       for (int n = 0; n < draw_data->CmdListsCount; n++)
352
       {
353
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
354
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
355
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
356
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
357
          {
358
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
359
             if (pcmd->UserCallback)
360
             {
361
                 pcmd->UserCallback(cmd_list, pcmd);
362
             }
363
             else
364
             {
365
                 // Project scissor/clipping rectangles into framebuffer space
366
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
367
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
368
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
369
                     continue;
370
371
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
372
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
373
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
374
                 // - Clipping coordinates are provided in imgui coordinates space:
375
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
376
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
377
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
378
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
379
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
380
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
381
382
                 // The texture for the draw call is specified by pcmd->GetTexID().
383
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
384
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
385
386
                 // Render 'pcmd->ElemCount/3' indexed triangles.
387
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
388
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
389
             }
390
          }
391
       }
392
    }
393
394
395
 API BREAKING CHANGES
396
 ====================
397
398
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
399
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
400
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
401
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
402
403
(Docking/Viewport Branch)
404
 - 2023/XX/XX (1.XXXX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
405
                          - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
406
                            you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
407
                          - likewise io.MousePos and GetMousePos() will use OS coordinates.
408
                            If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
409
410
 - 2023/06/28 (1.89.7) - overlapping items: obsoleted 'SetItemAllowOverlap()' (called after item) in favor of calling 'SetNextItemAllowOverlap()' (called before item). 'SetItemAllowOverlap()' didn't and couldn't work reliably since 1.89 (2022-11-15).
411
 - 2023/06/28 (1.89.7) - overlapping items: renamed 'ImGuiTreeNodeFlags_AllowItemOverlap' to 'ImGuiTreeNodeFlags_AllowOverlap', 'ImGuiSelectableFlags_AllowItemOverlap' to 'ImGuiSelectableFlags_AllowOverlap'. Kept redirecting enums (will obsolete).
412
 - 2023/06/28 (1.89.7) - overlapping items: IsItemHovered() now by default return false when querying an item using AllowOverlap mode which is being overlapped. Use ImGuiHoveredFlags_AllowWhenOverlappedByItem to revert to old behavior.
413
 - 2023/06/20 (1.89.7) - moved io.HoverDelayShort/io.HoverDelayNormal to style.HoverDelayShort/style.HoverDelayNormal. As the fields were added in 1.89 and expected to be left unchanged by most users, or only tweaked once during app initialization, we are exceptionally accepting the breakage.
414
 - 2023/05/30 (1.89.6) - backends: renamed "imgui_impl_sdlrenderer.cpp" to "imgui_impl_sdlrenderer2.cpp" and "imgui_impl_sdlrenderer.h" to "imgui_impl_sdlrenderer2.h". This is in prevision for the future release of SDL3.
415
 - 2023/05/22 (1.89.6) - listbox: commented out obsolete/redirecting functions that were marked obsolete more than two years ago:
416
                           - ListBoxHeader()  -> use BeginListBox() (note how two variants of ListBoxHeader() existed. Check commented versions in imgui.h for reference)
417
                           - ListBoxFooter()  -> use EndListBox()
418
 - 2023/05/15 (1.89.6) - clipper: commented out obsolete redirection constructor 'ImGuiListClipper(int items_count, float items_height = -1.0f)' that was marked obsolete in 1.79. Use default constructor + clipper.Begin().
419
 - 2023/05/15 (1.89.6) - clipper: renamed ImGuiListClipper::ForceDisplayRangeByIndices() to ImGuiListClipper::IncludeRangeByIndices().
420
 - 2023/03/14 (1.89.4) - commented out redirecting enums/functions names that were marked obsolete two years ago:
421
                           - ImGuiSliderFlags_ClampOnInput        -> use ImGuiSliderFlags_AlwaysClamp
422
                           - ImGuiInputTextFlags_AlwaysInsertMode -> use ImGuiInputTextFlags_AlwaysOverwrite
423
                           - ImDrawList::AddBezierCurve()         -> use ImDrawList::AddBezierCubic()
424
                           - ImDrawList::PathBezierCurveTo()      -> use ImDrawList::PathBezierCubicCurveTo()
425
 - 2023/03/09 (1.89.4) - renamed PushAllowKeyboardFocus()/PopAllowKeyboardFocus() to PushTabStop()/PopTabStop(). Kept inline redirection functions (will obsolete).
426
 - 2023/03/09 (1.89.4) - tooltips: Added 'bool' return value to BeginTooltip() for API consistency. Please only submit contents and call EndTooltip() if BeginTooltip() returns true. In reality the function will _currently_ always return true, but further changes down the line may change this, best to clarify API sooner.
427
 - 2023/02/15 (1.89.4) - moved the optional "courtesy maths operators" implementation from imgui_internal.h in imgui.h.
428
                         Even though we encourage using your own maths types and operators by setting up IM_VEC2_CLASS_EXTRA,
429
                         it has been frequently requested by people to use our own. We had an opt-in define which was
430
                         previously fulfilled in imgui_internal.h. It is now fulfilled in imgui.h. (#6164)
431
                           - OK:     #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui.h" / #include "imgui_internal.h"
432
                           - Error:  #include "imgui.h" / #define IMGUI_DEFINE_MATH_OPERATORS / #include "imgui_internal.h"
433
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
434
 - 2022/10/26 (1.89)   - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
435
 - 2022/10/12 (1.89)   - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
436
 - 2022/09/26 (1.89)   - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
437
                           - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
438
                           - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
439
                           - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
440
                           - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
441
                         the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
442
                         the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
443
                         exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
444
 - 2022/09/20 (1.89)   - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
445
                         this will require uses of legacy backend-dependent indices to be casted, e.g.
446
                            - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
447
                            - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
448
                            - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
449
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
450
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
451
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
452
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
453
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
454
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
455
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
456
                         - previously this would make the window content size ~200x200:
457
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
458
                         - instead, please submit an item:
459
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
460
                         - alternative:
461
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
462
                         - content size is now only extended when submitting an item!
463
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
464
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
465
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
466
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
467
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
468
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
469
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
470
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
471
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
472
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
473
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
474
                        - Official backends from 1.87+                  -> no issue.
475
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
476
                        - Custom backends not writing to io.NavInputs[] -> no issue.
477
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
478
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
479
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
480
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
481
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
482
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
483
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
484
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
485
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
486
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
487
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
488
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
489
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
490
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
491
                       read https://github.com/ocornut/imgui/issues/4921 for details.
492
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
493
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
494
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
495
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
496
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
497
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
498
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
499
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
500
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
501
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
502
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
503
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
504
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
505
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
506
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
507
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
508
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
509
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
510
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
511
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
512
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
513
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
514
                        - if you are using official backends from the source tree: you have nothing to do.
515
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
516
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
517
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
518
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
519
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
520
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
521
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
522
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
523
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
524
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
525
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
526
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
527
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
528
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
529
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
530
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
531
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
532
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
533
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
534
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
535
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
536
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
537
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
538
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
539
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
540
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
541
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
542
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
543
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
544
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
545
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
546
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
547
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
548
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
549
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
550
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
551
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
552
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
553
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
554
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
555
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
556
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
557
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
558
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
559
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
560
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
561
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
562
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
563
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
564
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
565
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
566
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
567
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
568
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
569
                       - if you omitted the 'power' parameter (likely!), you are not affected.
570
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
571
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
572
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
573
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
574
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
575
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
576
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
577
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
578
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
579
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
580
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
581
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
582
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
583
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
584
                       - ShowTestWindow()                    -> use ShowDemoWindow()
585
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
586
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
587
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
588
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
589
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
590
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
591
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
592
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
593
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
594
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
595
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
596
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
597
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
598
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
599
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
600
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
601
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
602
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
603
                       - ImFont::Glyph                       -> use ImFontGlyph
604
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
605
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
606
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
607
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
608
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
609
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
610
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
611
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
612
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
613
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
614
                       Please reach out if you are affected.
615
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
616
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
617
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
618
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
619
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
620
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
621
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
622
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
623
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
624
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
625
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
626
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
627
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
628
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
629
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
630
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
631
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
632
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
633
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
634
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
635
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
636
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
637
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
638
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
639
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
640
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
641
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
642
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
643
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
644
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
645
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
646
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
647
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
648
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
649
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
650
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
651
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
652
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
653
                       consistent with other functions. Kept redirection functions (will obsolete).
654
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
655
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
656
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
657
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
658
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
659
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
660
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
661
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
662
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
663
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
664
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
665
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
666
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
667
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
668
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
669
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
670
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
671
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
672
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
673
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
674
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
675
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
676
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
677
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
678
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
679
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
680
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
681
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
682
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
683
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
684
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
685
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
686
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
687
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
688
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
689
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
690
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
691
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
692
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
693
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
694
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
695
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
696
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
697
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
698
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
699
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
700
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
701
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
702
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
703
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
704
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
705
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
706
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
707
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
708
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
709
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
710
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
711
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
712
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
713
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
714
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
715
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
716
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
717
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
718
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
719
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
720
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
721
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
722
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
723
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
724
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
725
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
726
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
727
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
728
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
729
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
730
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
731
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
732
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
733
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
734
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
735
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
736
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
737
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
738
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
739
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
740
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
741
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
742
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
743
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
744
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
745
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
746
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
747
                     - the signature of the io.RenderDrawListsFn handler has changed!
748
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
749
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
750
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
751
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
752
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
753
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
754
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
755
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
756
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
757
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
758
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
759
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
760
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
761
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
762
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
763
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
764
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
765
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
766
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
767
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
768
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
769
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
770
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
771
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
772
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
773
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
774
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
775
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
776
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
777
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
778
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
779
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
780
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
781
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
782
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
783
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
784
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
785
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
786
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
787
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
788
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
789
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
790
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
791
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
792
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
793
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
794
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
795
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
796
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
797
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
798
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
799
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
800
801
802
 FREQUENTLY ASKED QUESTIONS (FAQ)
803
 ================================
804
805
 Read all answers online:
806
   https://www.dearimgui.com/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
807
 Read all answers locally (with a text editor or ideally a Markdown viewer):
808
   docs/FAQ.md
809
 Some answers are copied down here to facilitate searching in code.
810
811
 Q&A: Basics
812
 ===========
813
814
 Q: Where is the documentation?
815
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
816
    - Run the examples/ and explore them.
817
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
818
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
819
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
820
    - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
821
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
822
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
823
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
824
    - Your programming IDE is your friend, find the type or function declaration to find comments
825
      associated with it.
826
827
 Q: What is this library called?
828
 Q: Which version should I get?
829
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
830
 >> See https://www.dearimgui.com/faq for details.
831
832
 Q&A: Integration
833
 ================
834
835
 Q: How to get started?
836
 A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
837
838
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
839
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
840
 >> See https://www.dearimgui.com/faq for a fully detailed answer. You really want to read this.
841
842
 Q. How can I enable keyboard controls?
843
 Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
844
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
845
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
846
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
847
 >> See https://www.dearimgui.com/faq
848
849
 Q&A: Usage
850
 ----------
851
852
 Q: About the ID Stack system..
853
   - Why is my widget not reacting when I click on it?
854
   - How can I have widgets with an empty label?
855
   - How can I have multiple widgets with the same label?
856
   - How can I have multiple windows with the same label?
857
 Q: How can I display an image? What is ImTextureID, how does it work?
858
 Q: How can I use my own math types instead of ImVec2/ImVec4?
859
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
860
 Q: How can I display custom shapes? (using low-level ImDrawList API)
861
 >> See https://www.dearimgui.com/faq
862
863
 Q&A: Fonts, Text
864
 ================
865
866
 Q: How should I handle DPI in my application?
867
 Q: How can I load a different font than the default?
868
 Q: How can I easily use icons in my application?
869
 Q: How can I load multiple fonts?
870
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
871
 >> See https://www.dearimgui.com/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
872
873
 Q&A: Concerns
874
 =============
875
876
 Q: Who uses Dear ImGui?
877
 Q: Can you create elaborate/serious tools with Dear ImGui?
878
 Q: Can you reskin the look of Dear ImGui?
879
 Q: Why using C++ (as opposed to C)?
880
 >> See https://www.dearimgui.com/faq
881
882
 Q&A: Community
883
 ==============
884
885
 Q: How can I help?
886
 A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
887
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
888
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
889
    - Individuals: you can support continued development via PayPal donations. See README.
890
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
891
      and see how you want to help and can help!
892
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
893
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
894
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
895
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
896
897
*/
898
899
//-------------------------------------------------------------------------
900
// [SECTION] INCLUDES
901
//-------------------------------------------------------------------------
902
903
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
904
#define _CRT_SECURE_NO_WARNINGS
905
#endif
906
907
#ifndef IMGUI_DEFINE_MATH_OPERATORS
908
#define IMGUI_DEFINE_MATH_OPERATORS
909
#endif
910
911
#include "imgui.h"
912
#ifndef IMGUI_DISABLE
913
#include "imgui_internal.h"
914
915
// System includes
916
#include <stdio.h>      // vsnprintf, sscanf, printf
917
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
918
#include <stddef.h>     // intptr_t
919
#else
920
#include <stdint.h>     // intptr_t
921
#endif
922
923
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
924
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
925
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
926
#endif
927
928
// [Windows] OS specific includes (optional)
929
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
930
#define IMGUI_DISABLE_WIN32_FUNCTIONS
931
#endif
932
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
933
#ifndef WIN32_LEAN_AND_MEAN
934
#define WIN32_LEAN_AND_MEAN
935
#endif
936
#ifndef NOMINMAX
937
#define NOMINMAX
938
#endif
939
#ifndef __MINGW32__
940
#include <Windows.h>        // _wfopen, OpenClipboard
941
#else
942
#include <windows.h>
943
#endif
944
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
945
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
946
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
947
#endif
948
#endif
949
950
// [Apple] OS specific includes
951
#if defined(__APPLE__)
952
#include <TargetConditionals.h>
953
#endif
954
955
// Visual Studio warnings
956
#ifdef _MSC_VER
957
#pragma warning (disable: 4127)             // condition expression is constant
958
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
959
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
960
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
961
#endif
962
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
963
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
964
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
965
#endif
966
967
// Clang/GCC warnings with -Weverything
968
#if defined(__clang__)
969
#if __has_warning("-Wunknown-warning-option")
970
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
971
#endif
972
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
973
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
974
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
975
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
976
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
977
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
978
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
979
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
980
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
981
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
982
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
983
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
984
#elif defined(__GNUC__)
985
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
986
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
987
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
988
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
989
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
990
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
991
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
992
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
993
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
994
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
995
#endif
996
997
// Debug options
998
45.4k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
999
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
1000
1001
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
1002
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
1003
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
1004
1005
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
1006
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
1007
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
1008
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
1009
1010
// Tooltip offset
1011
static const ImVec2 TOOLTIP_DEFAULT_OFFSET = ImVec2(16, 10);            // Multiplied by g.Style.MouseCursorScale
1012
1013
// Docking
1014
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
1015
static const float DOCKING_SPLITTER_SIZE                    = 2.0f;
1016
1017
//-------------------------------------------------------------------------
1018
// [SECTION] FORWARD DECLARATIONS
1019
//-------------------------------------------------------------------------
1020
1021
static void             SetCurrentWindow(ImGuiWindow* window);
1022
static void             FindHoveredWindow();
1023
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
1024
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
1025
1026
static void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
1027
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
1028
1029
// Settings
1030
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
1031
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
1032
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
1033
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
1034
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
1035
1036
// Platform Dependents default implementation for IO functions
1037
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data_ctx);
1038
static void             SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text);
1039
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1040
1041
namespace ImGui
1042
{
1043
// Navigation
1044
static void             NavUpdate();
1045
static void             NavUpdateWindowing();
1046
static void             NavUpdateWindowingOverlay();
1047
static void             NavUpdateCancelRequest();
1048
static void             NavUpdateCreateMoveRequest();
1049
static void             NavUpdateCreateTabbingRequest();
1050
static float            NavUpdatePageUpPageDown();
1051
static inline void      NavUpdateAnyRequestFlag();
1052
static void             NavUpdateCreateWrappingRequest();
1053
static void             NavEndFrame();
1054
static bool             NavScoreItem(ImGuiNavItemData* result);
1055
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1056
static void             NavProcessItem();
1057
static void             NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags);
1058
static ImVec2           NavCalcPreferredRefPos();
1059
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1060
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1061
static void             NavRestoreLayer(ImGuiNavLayer layer);
1062
static void             NavRestoreHighlightAfterMove();
1063
static int              FindWindowFocusIndex(ImGuiWindow* window);
1064
1065
// Error Checking and Debug Tools
1066
static void             ErrorCheckNewFrameSanityChecks();
1067
static void             ErrorCheckEndFrameSanityChecks();
1068
static void             UpdateDebugToolItemPicker();
1069
static void             UpdateDebugToolStackQueries();
1070
1071
// Inputs
1072
static void             UpdateKeyboardInputs();
1073
static void             UpdateMouseInputs();
1074
static void             UpdateMouseWheel();
1075
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1076
1077
// Misc
1078
static void             UpdateSettings();
1079
static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1080
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1081
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1082
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1083
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1084
static void             RenderDimmedBackgrounds();
1085
1086
// Viewports
1087
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1088
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1089
static void             DestroyViewport(ImGuiViewportP* viewport);
1090
static void             UpdateViewportsNewFrame();
1091
static void             UpdateViewportsEndFrame();
1092
static void             WindowSelectViewport(ImGuiWindow* window);
1093
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1094
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1095
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1096
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1097
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1098
static int              FindPlatformMonitorForRect(const ImRect& r);
1099
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1100
1101
}
1102
1103
//-----------------------------------------------------------------------------
1104
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1105
//-----------------------------------------------------------------------------
1106
1107
// DLL users:
1108
// - Heaps and globals are not shared across DLL boundaries!
1109
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1110
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1111
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1112
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1113
1114
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1115
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1116
//   Change to a different context by calling ImGui::SetCurrentContext().
1117
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1118
//   If you want thread-safety to allow N threads to access N different contexts:
1119
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1120
//         struct ImGuiContext;
1121
//         extern thread_local ImGuiContext* MyImGuiTLS;
1122
//         #define GImGui MyImGuiTLS
1123
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1124
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1125
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1126
// - DLL users: read comments above.
1127
#ifndef GImGui
1128
ImGuiContext*   GImGui = NULL;
1129
#endif
1130
1131
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1132
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1133
// - DLL users: read comments above.
1134
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1135
1.22k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1136
1.17k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1137
#else
1138
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1139
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1140
#endif
1141
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1142
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1143
static void*                GImAllocatorUserData = NULL;
1144
1145
//-----------------------------------------------------------------------------
1146
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1147
//-----------------------------------------------------------------------------
1148
1149
ImGuiStyle::ImGuiStyle()
1150
1
{
1151
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1152
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1153
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1154
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1155
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1156
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1157
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1158
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1159
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1160
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1161
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1162
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1163
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1164
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1165
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1166
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1167
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1168
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell
1169
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1170
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1171
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1172
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1173
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1174
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1175
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1176
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1177
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1178
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1179
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1180
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1181
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1182
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1183
1
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1184
1
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1185
1
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1186
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1187
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1188
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1189
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1190
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1191
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1192
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1193
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1194
1195
    // Behaviors
1196
1
    HoverStationaryDelay    = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_Stationary). Time required to consider mouse stationary.
1197
1
    HoverDelayShort         = 0.15f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayShort). Usually used along with HoverStationaryDelay.
1198
1
    HoverDelayNormal        = 0.40f;            // Delay for IsItemHovered(ImGuiHoveredFlags_DelayNormal). "
1199
1
    HoverFlagsForTooltipMouse = ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort;    // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using mouse.
1200
1
    HoverFlagsForTooltipNav = ImGuiHoveredFlags_NoSharedDelay | ImGuiHoveredFlags_DelayNormal;  // Default flags when using IsItemHovered(ImGuiHoveredFlags_ForTooltip) or BeginItemTooltip()/SetItemTooltip() while using keyboard/gamepad.
1201
1202
    // Default theme
1203
1
    ImGui::StyleColorsDark(this);
1204
1
}
1205
1206
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1207
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1208
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1209
0
{
1210
0
    WindowPadding = ImFloor(WindowPadding * scale_factor);
1211
0
    WindowRounding = ImFloor(WindowRounding * scale_factor);
1212
0
    WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1213
0
    ChildRounding = ImFloor(ChildRounding * scale_factor);
1214
0
    PopupRounding = ImFloor(PopupRounding * scale_factor);
1215
0
    FramePadding = ImFloor(FramePadding * scale_factor);
1216
0
    FrameRounding = ImFloor(FrameRounding * scale_factor);
1217
0
    ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1218
0
    ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1219
0
    CellPadding = ImFloor(CellPadding * scale_factor);
1220
0
    TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1221
0
    IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1222
0
    ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1223
0
    ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1224
0
    ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1225
0
    GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1226
0
    GrabRounding = ImFloor(GrabRounding * scale_factor);
1227
0
    LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
1228
0
    TabRounding = ImFloor(TabRounding * scale_factor);
1229
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1230
0
    SeparatorTextPadding = ImFloor(SeparatorTextPadding * scale_factor);
1231
0
    DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1232
0
    DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1233
0
    MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1234
0
}
1235
1236
ImGuiIO::ImGuiIO()
1237
1
{
1238
    // Most fields are initialized with zero
1239
1
    memset(this, 0, sizeof(*this));
1240
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1241
1242
    // Settings
1243
1
    ConfigFlags = ImGuiConfigFlags_None;
1244
1
    BackendFlags = ImGuiBackendFlags_None;
1245
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1246
1
    DeltaTime = 1.0f / 60.0f;
1247
1
    IniSavingRate = 5.0f;
1248
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1249
1
    LogFilename = "imgui_log.txt";
1250
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1251
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1252
        KeyMap[i] = -1;
1253
#endif
1254
1
    UserData = NULL;
1255
1256
1
    Fonts = NULL;
1257
1
    FontGlobalScale = 1.0f;
1258
1
    FontDefault = NULL;
1259
1
    FontAllowUserScaling = false;
1260
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1261
1262
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1263
1
    ConfigDockingNoSplit = false;
1264
1
    ConfigDockingWithShift = false;
1265
1
    ConfigDockingAlwaysTabBar = false;
1266
1
    ConfigDockingTransparentPayload = false;
1267
1268
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1269
1
    ConfigViewportsNoAutoMerge = false;
1270
1
    ConfigViewportsNoTaskBarIcon = false;
1271
1
    ConfigViewportsNoDecoration = true;
1272
1
    ConfigViewportsNoDefaultParent = false;
1273
1274
    // Miscellaneous options
1275
1
    MouseDrawCursor = false;
1276
#ifdef __APPLE__
1277
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1278
#else
1279
1
    ConfigMacOSXBehaviors = false;
1280
1
#endif
1281
1
    ConfigInputTrickleEventQueue = true;
1282
1
    ConfigInputTextCursorBlink = true;
1283
1
    ConfigInputTextEnterKeepActive = false;
1284
1
    ConfigDragClickToInputText = false;
1285
1
    ConfigWindowsResizeFromEdges = true;
1286
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1287
1
    ConfigMemoryCompactTimer = 60.0f;
1288
1
    ConfigDebugBeginReturnValueOnce = false;
1289
1
    ConfigDebugBeginReturnValueLoop = false;
1290
1291
    // Inputs Behaviors
1292
1
    MouseDoubleClickTime = 0.30f;
1293
1
    MouseDoubleClickMaxDist = 6.0f;
1294
1
    MouseDragThreshold = 6.0f;
1295
1
    KeyRepeatDelay = 0.275f;
1296
1
    KeyRepeatRate = 0.050f;
1297
1298
    // Platform Functions
1299
    // Note: Initialize() will setup default clipboard/ime handlers.
1300
1
    BackendPlatformName = BackendRendererName = NULL;
1301
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1302
1303
    // Input (NB: we already have memset zero the entire structure!)
1304
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1305
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1306
1
    MouseSource = ImGuiMouseSource_Mouse;
1307
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1308
141
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1309
1
    AppAcceptingEvents = true;
1310
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1311
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1312
1
}
1313
1314
// Pass in translated ASCII characters for text input.
1315
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1316
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1317
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1318
void ImGuiIO::AddInputCharacter(unsigned int c)
1319
3.49k
{
1320
3.49k
    IM_ASSERT(Ctx != NULL);
1321
3.49k
    ImGuiContext& g = *Ctx;
1322
3.49k
    if (c == 0 || !AppAcceptingEvents)
1323
228
        return;
1324
1325
3.26k
    ImGuiInputEvent e;
1326
3.26k
    e.Type = ImGuiInputEventType_Text;
1327
3.26k
    e.Source = ImGuiInputSource_Keyboard;
1328
3.26k
    e.EventId = g.InputEventsNextEventId++;
1329
3.26k
    e.Text.Char = c;
1330
3.26k
    g.InputEventsQueue.push_back(e);
1331
3.26k
}
1332
1333
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1334
// we should save the high surrogate.
1335
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1336
3.33k
{
1337
3.33k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1338
182
        return;
1339
1340
3.15k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1341
493
    {
1342
493
        if (InputQueueSurrogate != 0)
1343
299
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1344
493
        InputQueueSurrogate = c;
1345
493
        return;
1346
493
    }
1347
1348
2.66k
    ImWchar cp = c;
1349
2.66k
    if (InputQueueSurrogate != 0)
1350
180
    {
1351
180
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1352
162
        {
1353
162
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1354
162
        }
1355
18
        else
1356
18
        {
1357
18
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1358
18
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1359
#else
1360
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1361
#endif
1362
18
        }
1363
1364
180
        InputQueueSurrogate = 0;
1365
180
    }
1366
2.66k
    AddInputCharacter((unsigned)cp);
1367
2.66k
}
1368
1369
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1370
36
{
1371
36
    if (!AppAcceptingEvents)
1372
0
        return;
1373
36
    while (*utf8_chars != 0)
1374
0
    {
1375
0
        unsigned int c = 0;
1376
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1377
0
        AddInputCharacter(c);
1378
0
    }
1379
36
}
1380
1381
// FIXME: Perhaps we could clear queued events as well?
1382
void ImGuiIO::ClearInputCharacters()
1383
5.51k
{
1384
5.51k
    InputQueueCharacters.resize(0);
1385
5.51k
}
1386
1387
// FIXME: Perhaps we could clear queued events as well?
1388
void ImGuiIO::ClearInputKeys()
1389
5.72k
{
1390
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1391
    memset(KeysDown, 0, sizeof(KeysDown));
1392
#endif
1393
807k
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1394
801k
    {
1395
801k
        KeysData[n].Down             = false;
1396
801k
        KeysData[n].DownDuration     = -1.0f;
1397
801k
        KeysData[n].DownDurationPrev = -1.0f;
1398
801k
    }
1399
5.72k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1400
5.72k
    KeyMods = ImGuiMod_None;
1401
5.72k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1402
34.3k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1403
28.6k
    {
1404
28.6k
        MouseDown[n] = false;
1405
28.6k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1406
28.6k
    }
1407
5.72k
    MouseWheel = MouseWheelH = 0.0f;
1408
5.72k
}
1409
1410
static ImGuiInputEvent* FindLatestInputEvent(ImGuiContext* ctx, ImGuiInputEventType type, int arg = -1)
1411
5.65k
{
1412
5.65k
    ImGuiContext& g = *ctx;
1413
8.50k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1414
4.86k
    {
1415
4.86k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1416
4.86k
        if (e->Type != type)
1417
1.77k
            continue;
1418
3.08k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1419
330
            continue;
1420
2.75k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1421
750
            continue;
1422
2.00k
        return e;
1423
2.75k
    }
1424
3.64k
    return NULL;
1425
5.65k
}
1426
1427
// Queue a new key down/up event.
1428
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1429
// - bool down:          Is the key down? use false to signify a key release.
1430
// - float analog_value: 0.0f..1.0f
1431
// IMPORTANT: THIS FUNCTION AND OTHER "ADD" GRABS THE CONTEXT FROM OUR INSTANCE.
1432
// WE NEED TO ENSURE THAT ALL FUNCTION CALLS ARE FULLFILLING THIS, WHICH IS WHY GetKeyData() HAS AN EXPLICIT CONTEXT.
1433
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1434
1.24k
{
1435
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1436
1.24k
    IM_ASSERT(Ctx != NULL);
1437
1.24k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1438
0
        return;
1439
1.24k
    ImGuiContext& g = *Ctx;
1440
1.24k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1441
1.24k
    IM_ASSERT(ImGui::IsAliasKey(key) == false); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1442
1.24k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1443
1444
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1445
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1446
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1447
    if (BackendUsingLegacyKeyArrays == -1)
1448
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1449
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1450
    BackendUsingLegacyKeyArrays = 0;
1451
#endif
1452
1.24k
    if (ImGui::IsGamepadKey(key))
1453
56
        BackendUsingLegacyNavInputArray = false;
1454
1455
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1456
1.24k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Key, (int)key);
1457
1.24k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(&g, key);
1458
1.24k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1459
1.24k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1460
1.24k
    if (latest_key_down == down && latest_key_analog == analog_value)
1461
189
        return;
1462
1463
    // Add event
1464
1.05k
    ImGuiInputEvent e;
1465
1.05k
    e.Type = ImGuiInputEventType_Key;
1466
1.05k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1467
1.05k
    e.EventId = g.InputEventsNextEventId++;
1468
1.05k
    e.Key.Key = key;
1469
1.05k
    e.Key.Down = down;
1470
1.05k
    e.Key.AnalogValue = analog_value;
1471
1.05k
    g.InputEventsQueue.push_back(e);
1472
1.05k
}
1473
1474
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1475
924
{
1476
924
    if (!AppAcceptingEvents)
1477
0
        return;
1478
924
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1479
924
}
1480
1481
// [Optional] Call after AddKeyEvent().
1482
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1483
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1484
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1485
0
{
1486
0
    if (key == ImGuiKey_None)
1487
0
        return;
1488
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1489
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1490
0
    IM_UNUSED(native_keycode);  // Yet unused
1491
0
    IM_UNUSED(native_scancode); // Yet unused
1492
1493
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1494
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1495
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1496
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1497
        return;
1498
    KeyMap[legacy_key] = key;
1499
    KeyMap[key] = legacy_key;
1500
#else
1501
0
    IM_UNUSED(key);
1502
0
    IM_UNUSED(native_legacy_index);
1503
0
#endif
1504
0
}
1505
1506
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1507
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1508
0
{
1509
0
    AppAcceptingEvents = accepting_events;
1510
0
}
1511
1512
// Queue a mouse move event
1513
void ImGuiIO::AddMousePosEvent(float x, float y)
1514
1.48k
{
1515
1.48k
    IM_ASSERT(Ctx != NULL);
1516
1.48k
    ImGuiContext& g = *Ctx;
1517
1.48k
    if (!AppAcceptingEvents)
1518
0
        return;
1519
1520
    // Apply same flooring as UpdateMouseInputs()
1521
1.48k
    ImVec2 pos((x > -FLT_MAX) ? ImFloorSigned(x) : x, (y > -FLT_MAX) ? ImFloorSigned(y) : y);
1522
1523
    // Filter duplicate
1524
1.48k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MousePos);
1525
1.48k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1526
1.48k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1527
386
        return;
1528
1529
1.09k
    ImGuiInputEvent e;
1530
1.09k
    e.Type = ImGuiInputEventType_MousePos;
1531
1.09k
    e.Source = ImGuiInputSource_Mouse;
1532
1.09k
    e.EventId = g.InputEventsNextEventId++;
1533
1.09k
    e.MousePos.PosX = pos.x;
1534
1.09k
    e.MousePos.PosY = pos.y;
1535
1.09k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1536
1.09k
    g.InputEventsQueue.push_back(e);
1537
1.09k
}
1538
1539
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1540
2.31k
{
1541
2.31k
    IM_ASSERT(Ctx != NULL);
1542
2.31k
    ImGuiContext& g = *Ctx;
1543
2.31k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1544
2.31k
    if (!AppAcceptingEvents)
1545
0
        return;
1546
1547
    // Filter duplicate
1548
2.31k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseButton, (int)mouse_button);
1549
2.31k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1550
2.31k
    if (latest_button_down == down)
1551
972
        return;
1552
1553
1.34k
    ImGuiInputEvent e;
1554
1.34k
    e.Type = ImGuiInputEventType_MouseButton;
1555
1.34k
    e.Source = ImGuiInputSource_Mouse;
1556
1.34k
    e.EventId = g.InputEventsNextEventId++;
1557
1.34k
    e.MouseButton.Button = mouse_button;
1558
1.34k
    e.MouseButton.Down = down;
1559
1.34k
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1560
1.34k
    g.InputEventsQueue.push_back(e);
1561
1.34k
}
1562
1563
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1564
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1565
488
{
1566
488
    IM_ASSERT(Ctx != NULL);
1567
488
    ImGuiContext& g = *Ctx;
1568
1569
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1570
488
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1571
19
        return;
1572
1573
469
    ImGuiInputEvent e;
1574
469
    e.Type = ImGuiInputEventType_MouseWheel;
1575
469
    e.Source = ImGuiInputSource_Mouse;
1576
469
    e.EventId = g.InputEventsNextEventId++;
1577
469
    e.MouseWheel.WheelX = wheel_x;
1578
469
    e.MouseWheel.WheelY = wheel_y;
1579
469
    e.MouseWheel.MouseSource = g.InputEventsNextMouseSource;
1580
469
    g.InputEventsQueue.push_back(e);
1581
469
}
1582
1583
// This is not a real event, the data is latched in order to be stored in actual Mouse events.
1584
// This is so that duplicate events (e.g. Windows sending extraneous WM_MOUSEMOVE) gets filtered and are not leading to actual source changes.
1585
void ImGuiIO::AddMouseSourceEvent(ImGuiMouseSource source)
1586
0
{
1587
0
    IM_ASSERT(Ctx != NULL);
1588
0
    ImGuiContext& g = *Ctx;
1589
0
    g.InputEventsNextMouseSource = source;
1590
0
}
1591
1592
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1593
0
{
1594
0
    IM_ASSERT(Ctx != NULL);
1595
0
    ImGuiContext& g = *Ctx;
1596
    //IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1597
0
    if (!AppAcceptingEvents)
1598
0
        return;
1599
1600
    // Filter duplicate
1601
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_MouseViewport);
1602
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1603
0
    if (latest_viewport_id == viewport_id)
1604
0
        return;
1605
1606
0
    ImGuiInputEvent e;
1607
0
    e.Type = ImGuiInputEventType_MouseViewport;
1608
0
    e.Source = ImGuiInputSource_Mouse;
1609
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1610
0
    g.InputEventsQueue.push_back(e);
1611
0
}
1612
1613
void ImGuiIO::AddFocusEvent(bool focused)
1614
608
{
1615
608
    IM_ASSERT(Ctx != NULL);
1616
608
    ImGuiContext& g = *Ctx;
1617
1618
    // Filter duplicate
1619
608
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(&g, ImGuiInputEventType_Focus);
1620
608
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1621
608
    if (latest_focused == focused || (ConfigDebugIgnoreFocusLoss && !focused))
1622
246
        return;
1623
1624
362
    ImGuiInputEvent e;
1625
362
    e.Type = ImGuiInputEventType_Focus;
1626
362
    e.EventId = g.InputEventsNextEventId++;
1627
362
    e.AppFocused.Focused = focused;
1628
362
    g.InputEventsQueue.push_back(e);
1629
362
}
1630
1631
//-----------------------------------------------------------------------------
1632
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1633
//-----------------------------------------------------------------------------
1634
1635
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1636
0
{
1637
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1638
0
    ImVec2 p_last = p1;
1639
0
    ImVec2 p_closest;
1640
0
    float p_closest_dist2 = FLT_MAX;
1641
0
    float t_step = 1.0f / (float)num_segments;
1642
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1643
0
    {
1644
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1645
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1646
0
        float dist2 = ImLengthSqr(p - p_line);
1647
0
        if (dist2 < p_closest_dist2)
1648
0
        {
1649
0
            p_closest = p_line;
1650
0
            p_closest_dist2 = dist2;
1651
0
        }
1652
0
        p_last = p_current;
1653
0
    }
1654
0
    return p_closest;
1655
0
}
1656
1657
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1658
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1659
0
{
1660
0
    float dx = x4 - x1;
1661
0
    float dy = y4 - y1;
1662
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1663
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1664
0
    d2 = (d2 >= 0) ? d2 : -d2;
1665
0
    d3 = (d3 >= 0) ? d3 : -d3;
1666
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1667
0
    {
1668
0
        ImVec2 p_current(x4, y4);
1669
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1670
0
        float dist2 = ImLengthSqr(p - p_line);
1671
0
        if (dist2 < p_closest_dist2)
1672
0
        {
1673
0
            p_closest = p_line;
1674
0
            p_closest_dist2 = dist2;
1675
0
        }
1676
0
        p_last = p_current;
1677
0
    }
1678
0
    else if (level < 10)
1679
0
    {
1680
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1681
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1682
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1683
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1684
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1685
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1686
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1687
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1688
0
    }
1689
0
}
1690
1691
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1692
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1693
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1694
0
{
1695
0
    IM_ASSERT(tess_tol > 0.0f);
1696
0
    ImVec2 p_last = p1;
1697
0
    ImVec2 p_closest;
1698
0
    float p_closest_dist2 = FLT_MAX;
1699
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1700
0
    return p_closest;
1701
0
}
1702
1703
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1704
0
{
1705
0
    ImVec2 ap = p - a;
1706
0
    ImVec2 ab_dir = b - a;
1707
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1708
0
    if (dot < 0.0f)
1709
0
        return a;
1710
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1711
0
    if (dot > ab_len_sqr)
1712
0
        return b;
1713
0
    return a + ab_dir * dot / ab_len_sqr;
1714
0
}
1715
1716
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1717
0
{
1718
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1719
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1720
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1721
0
    return ((b1 == b2) && (b2 == b3));
1722
0
}
1723
1724
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1725
0
{
1726
0
    ImVec2 v0 = b - a;
1727
0
    ImVec2 v1 = c - a;
1728
0
    ImVec2 v2 = p - a;
1729
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1730
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1731
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1732
0
    out_u = 1.0f - out_v - out_w;
1733
0
}
1734
1735
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1736
0
{
1737
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1738
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1739
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1740
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1741
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1742
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1743
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1744
0
    if (m == dist2_ab)
1745
0
        return proj_ab;
1746
0
    if (m == dist2_bc)
1747
0
        return proj_bc;
1748
0
    return proj_ca;
1749
0
}
1750
1751
//-----------------------------------------------------------------------------
1752
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1753
//-----------------------------------------------------------------------------
1754
1755
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1756
int ImStricmp(const char* str1, const char* str2)
1757
0
{
1758
0
    int d;
1759
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1760
0
    return d;
1761
0
}
1762
1763
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1764
0
{
1765
0
    int d = 0;
1766
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1767
0
    return d;
1768
0
}
1769
1770
void ImStrncpy(char* dst, const char* src, size_t count)
1771
5
{
1772
5
    if (count < 1)
1773
0
        return;
1774
5
    if (count > 1)
1775
5
        strncpy(dst, src, count - 1);
1776
5
    dst[count - 1] = 0;
1777
5
}
1778
1779
char* ImStrdup(const char* str)
1780
3
{
1781
3
    size_t len = strlen(str);
1782
3
    void* buf = IM_ALLOC(len + 1);
1783
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1784
3
}
1785
1786
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1787
0
{
1788
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1789
0
    size_t src_size = strlen(src) + 1;
1790
0
    if (dst_buf_size < src_size)
1791
0
    {
1792
0
        IM_FREE(dst);
1793
0
        dst = (char*)IM_ALLOC(src_size);
1794
0
        if (p_dst_size)
1795
0
            *p_dst_size = src_size;
1796
0
    }
1797
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1798
0
}
1799
1800
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1801
0
{
1802
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1803
0
    return p;
1804
0
}
1805
1806
int ImStrlenW(const ImWchar* str)
1807
0
{
1808
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1809
0
    int n = 0;
1810
0
    while (*str++) n++;
1811
0
    return n;
1812
0
}
1813
1814
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1815
const char* ImStreolRange(const char* str, const char* str_end)
1816
0
{
1817
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1818
0
    return p ? p : str_end;
1819
0
}
1820
1821
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1822
0
{
1823
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1824
0
        buf_mid_line--;
1825
0
    return buf_mid_line;
1826
0
}
1827
1828
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1829
0
{
1830
0
    if (!needle_end)
1831
0
        needle_end = needle + strlen(needle);
1832
1833
0
    const char un0 = (char)ImToUpper(*needle);
1834
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1835
0
    {
1836
0
        if (ImToUpper(*haystack) == un0)
1837
0
        {
1838
0
            const char* b = needle + 1;
1839
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1840
0
                if (ImToUpper(*a) != ImToUpper(*b))
1841
0
                    break;
1842
0
            if (b == needle_end)
1843
0
                return haystack;
1844
0
        }
1845
0
        haystack++;
1846
0
    }
1847
0
    return NULL;
1848
0
}
1849
1850
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1851
void ImStrTrimBlanks(char* buf)
1852
0
{
1853
0
    char* p = buf;
1854
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1855
0
        p++;
1856
0
    char* p_start = p;
1857
0
    while (*p != 0)                         // Find end of string
1858
0
        p++;
1859
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1860
0
        p--;
1861
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1862
0
        memmove(buf, p_start, p - p_start);
1863
0
    buf[p - p_start] = 0;                   // Zero terminate
1864
0
}
1865
1866
const char* ImStrSkipBlank(const char* str)
1867
0
{
1868
0
    while (str[0] == ' ' || str[0] == '\t')
1869
0
        str++;
1870
0
    return str;
1871
0
}
1872
1873
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1874
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1875
// B) When buf==NULL vsnprintf() will return the output size.
1876
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1877
1878
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1879
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1880
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1881
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1882
#ifdef IMGUI_USE_STB_SPRINTF
1883
#define STB_SPRINTF_IMPLEMENTATION
1884
#ifdef IMGUI_STB_SPRINTF_FILENAME
1885
#include IMGUI_STB_SPRINTF_FILENAME
1886
#else
1887
#include "stb_sprintf.h"
1888
#endif
1889
#endif
1890
1891
#if defined(_MSC_VER) && !defined(vsnprintf)
1892
#define vsnprintf _vsnprintf
1893
#endif
1894
1895
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1896
1
{
1897
1
    va_list args;
1898
1
    va_start(args, fmt);
1899
#ifdef IMGUI_USE_STB_SPRINTF
1900
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1901
#else
1902
1
    int w = vsnprintf(buf, buf_size, fmt, args);
1903
1
#endif
1904
1
    va_end(args);
1905
1
    if (buf == NULL)
1906
0
        return w;
1907
1
    if (w == -1 || w >= (int)buf_size)
1908
0
        w = (int)buf_size - 1;
1909
1
    buf[w] = 0;
1910
1
    return w;
1911
1
}
1912
1913
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1914
9.51k
{
1915
#ifdef IMGUI_USE_STB_SPRINTF
1916
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1917
#else
1918
9.51k
    int w = vsnprintf(buf, buf_size, fmt, args);
1919
9.51k
#endif
1920
9.51k
    if (buf == NULL)
1921
0
        return w;
1922
9.51k
    if (w == -1 || w >= (int)buf_size)
1923
0
        w = (int)buf_size - 1;
1924
9.51k
    buf[w] = 0;
1925
9.51k
    return w;
1926
9.51k
}
1927
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1928
1929
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1930
9.51k
{
1931
9.51k
    ImGuiContext& g = *GImGui;
1932
9.51k
    va_list args;
1933
9.51k
    va_start(args, fmt);
1934
9.51k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1935
0
    {
1936
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1937
0
        *out_buf = buf;
1938
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1939
0
    }
1940
9.51k
    else
1941
9.51k
    {
1942
9.51k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1943
9.51k
        *out_buf = g.TempBuffer.Data;
1944
9.51k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1945
9.51k
    }
1946
9.51k
    va_end(args);
1947
9.51k
}
1948
1949
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1950
0
{
1951
0
    ImGuiContext& g = *GImGui;
1952
0
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1953
0
    {
1954
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1955
0
        *out_buf = buf;
1956
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1957
0
    }
1958
0
    else
1959
0
    {
1960
0
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1961
0
        *out_buf = g.TempBuffer.Data;
1962
0
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1963
0
    }
1964
0
}
1965
1966
// CRC32 needs a 1KB lookup table (not cache friendly)
1967
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1968
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1969
static const ImU32 GCrc32LookupTable[256] =
1970
{
1971
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1972
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1973
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1974
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1975
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1976
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1977
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1978
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1979
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1980
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1981
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1982
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1983
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1984
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1985
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1986
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1987
};
1988
1989
// Known size hash
1990
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1991
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1992
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
1993
9.51k
{
1994
9.51k
    ImU32 crc = ~seed;
1995
9.51k
    const unsigned char* data = (const unsigned char*)data_p;
1996
9.51k
    const ImU32* crc32_lut = GCrc32LookupTable;
1997
47.5k
    while (data_size-- != 0)
1998
38.0k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1999
9.51k
    return ~crc;
2000
9.51k
}
2001
2002
// Zero-terminated string hash, with support for ### to reset back to seed value
2003
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
2004
// Because this syntax is rarely used we are optimizing for the common case.
2005
// - If we reach ### in the string we discard the hash so far and reset to the seed.
2006
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
2007
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
2008
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
2009
155k
{
2010
155k
    seed = ~seed;
2011
155k
    ImU32 crc = seed;
2012
155k
    const unsigned char* data = (const unsigned char*)data_p;
2013
155k
    const ImU32* crc32_lut = GCrc32LookupTable;
2014
155k
    if (data_size != 0)
2015
0
    {
2016
0
        while (data_size-- != 0)
2017
0
        {
2018
0
            unsigned char c = *data++;
2019
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
2020
0
                crc = seed;
2021
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2022
0
        }
2023
0
    }
2024
155k
    else
2025
155k
    {
2026
2.07M
        while (unsigned char c = *data++)
2027
1.91M
        {
2028
1.91M
            if (c == '#' && data[0] == '#' && data[1] == '#')
2029
18.0k
                crc = seed;
2030
1.91M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
2031
1.91M
        }
2032
155k
    }
2033
155k
    return ~crc;
2034
155k
}
2035
2036
//-----------------------------------------------------------------------------
2037
// [SECTION] MISC HELPERS/UTILITIES (File functions)
2038
//-----------------------------------------------------------------------------
2039
2040
// Default file functions
2041
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2042
2043
ImFileHandle ImFileOpen(const char* filename, const char* mode)
2044
0
{
2045
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
2046
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
2047
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
2048
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
2049
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
2050
    ImVector<wchar_t> buf;
2051
    buf.resize(filename_wsize + mode_wsize);
2052
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
2053
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
2054
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
2055
#else
2056
0
    return fopen(filename, mode);
2057
0
#endif
2058
0
}
2059
2060
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
2061
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
2062
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
2063
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2064
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2065
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2066
2067
// Helper: Load file content into memory
2068
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2069
// This can't really be used with "rt" because fseek size won't match read size.
2070
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2071
0
{
2072
0
    IM_ASSERT(filename && mode);
2073
0
    if (out_file_size)
2074
0
        *out_file_size = 0;
2075
2076
0
    ImFileHandle f;
2077
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2078
0
        return NULL;
2079
2080
0
    size_t file_size = (size_t)ImFileGetSize(f);
2081
0
    if (file_size == (size_t)-1)
2082
0
    {
2083
0
        ImFileClose(f);
2084
0
        return NULL;
2085
0
    }
2086
2087
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2088
0
    if (file_data == NULL)
2089
0
    {
2090
0
        ImFileClose(f);
2091
0
        return NULL;
2092
0
    }
2093
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2094
0
    {
2095
0
        ImFileClose(f);
2096
0
        IM_FREE(file_data);
2097
0
        return NULL;
2098
0
    }
2099
0
    if (padding_bytes > 0)
2100
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2101
2102
0
    ImFileClose(f);
2103
0
    if (out_file_size)
2104
0
        *out_file_size = file_size;
2105
2106
0
    return file_data;
2107
0
}
2108
2109
//-----------------------------------------------------------------------------
2110
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2111
//-----------------------------------------------------------------------------
2112
2113
IM_MSVC_RUNTIME_CHECKS_OFF
2114
2115
// Convert UTF-8 to 32-bit character, process single character input.
2116
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2117
// We handle UTF-8 decoding error by skipping forward.
2118
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2119
57.9k
{
2120
57.9k
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2121
57.9k
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2122
57.9k
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2123
57.9k
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2124
57.9k
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2125
57.9k
    int len = lengths[*(const unsigned char*)in_text >> 3];
2126
57.9k
    int wanted = len + (len ? 0 : 1);
2127
2128
57.9k
    if (in_text_end == NULL)
2129
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2130
2131
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2132
    // so it is fast even with excessive branching.
2133
57.9k
    unsigned char s[4];
2134
57.9k
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2135
57.9k
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2136
57.9k
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2137
57.9k
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2138
2139
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2140
57.9k
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2141
57.9k
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2142
57.9k
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2143
57.9k
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2144
57.9k
    *out_char >>= shiftc[len];
2145
2146
    // Accumulate the various error conditions.
2147
57.9k
    int e = 0;
2148
57.9k
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2149
57.9k
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2150
57.9k
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2151
57.9k
    e |= (s[1] & 0xc0) >> 2;
2152
57.9k
    e |= (s[2] & 0xc0) >> 4;
2153
57.9k
    e |= (s[3]       ) >> 6;
2154
57.9k
    e ^= 0x2a; // top two bits of each tail byte correct?
2155
57.9k
    e >>= shifte[len];
2156
2157
57.9k
    if (e)
2158
387
    {
2159
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2160
        // One byte is consumed in case of invalid first byte of in_text.
2161
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2162
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2163
387
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2164
387
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2165
387
    }
2166
2167
57.9k
    return wanted;
2168
57.9k
}
2169
2170
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2171
0
{
2172
0
    ImWchar* buf_out = buf;
2173
0
    ImWchar* buf_end = buf + buf_size;
2174
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2175
0
    {
2176
0
        unsigned int c;
2177
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2178
0
        *buf_out++ = (ImWchar)c;
2179
0
    }
2180
0
    *buf_out = 0;
2181
0
    if (in_text_remaining)
2182
0
        *in_text_remaining = in_text;
2183
0
    return (int)(buf_out - buf);
2184
0
}
2185
2186
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2187
0
{
2188
0
    int char_count = 0;
2189
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2190
0
    {
2191
0
        unsigned int c;
2192
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2193
0
        char_count++;
2194
0
    }
2195
0
    return char_count;
2196
0
}
2197
2198
// Based on stb_to_utf8() from github.com/nothings/stb/
2199
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2200
0
{
2201
0
    if (c < 0x80)
2202
0
    {
2203
0
        buf[0] = (char)c;
2204
0
        return 1;
2205
0
    }
2206
0
    if (c < 0x800)
2207
0
    {
2208
0
        if (buf_size < 2) return 0;
2209
0
        buf[0] = (char)(0xc0 + (c >> 6));
2210
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2211
0
        return 2;
2212
0
    }
2213
0
    if (c < 0x10000)
2214
0
    {
2215
0
        if (buf_size < 3) return 0;
2216
0
        buf[0] = (char)(0xe0 + (c >> 12));
2217
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2218
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2219
0
        return 3;
2220
0
    }
2221
0
    if (c <= 0x10FFFF)
2222
0
    {
2223
0
        if (buf_size < 4) return 0;
2224
0
        buf[0] = (char)(0xf0 + (c >> 18));
2225
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2226
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2227
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2228
0
        return 4;
2229
0
    }
2230
    // Invalid code point, the max unicode is 0x10FFFF
2231
0
    return 0;
2232
0
}
2233
2234
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2235
0
{
2236
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2237
0
    out_buf[count] = 0;
2238
0
    return out_buf;
2239
0
}
2240
2241
// Not optimal but we very rarely use this function.
2242
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2243
0
{
2244
0
    unsigned int unused = 0;
2245
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2246
0
}
2247
2248
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2249
0
{
2250
0
    if (c < 0x80) return 1;
2251
0
    if (c < 0x800) return 2;
2252
0
    if (c < 0x10000) return 3;
2253
0
    if (c <= 0x10FFFF) return 4;
2254
0
    return 3;
2255
0
}
2256
2257
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2258
0
{
2259
0
    char* buf_p = out_buf;
2260
0
    const char* buf_end = out_buf + out_buf_size;
2261
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2262
0
    {
2263
0
        unsigned int c = (unsigned int)(*in_text++);
2264
0
        if (c < 0x80)
2265
0
            *buf_p++ = (char)c;
2266
0
        else
2267
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2268
0
    }
2269
0
    *buf_p = 0;
2270
0
    return (int)(buf_p - out_buf);
2271
0
}
2272
2273
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2274
0
{
2275
0
    int bytes_count = 0;
2276
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2277
0
    {
2278
0
        unsigned int c = (unsigned int)(*in_text++);
2279
0
        if (c < 0x80)
2280
0
            bytes_count++;
2281
0
        else
2282
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2283
0
    }
2284
0
    return bytes_count;
2285
0
}
2286
IM_MSVC_RUNTIME_CHECKS_RESTORE
2287
2288
//-----------------------------------------------------------------------------
2289
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2290
// Note: The Convert functions are early design which are not consistent with other API.
2291
//-----------------------------------------------------------------------------
2292
2293
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2294
0
{
2295
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2296
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2297
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2298
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2299
0
    return IM_COL32(r, g, b, 0xFF);
2300
0
}
2301
2302
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2303
95.2k
{
2304
95.2k
    float s = 1.0f / 255.0f;
2305
95.2k
    return ImVec4(
2306
95.2k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2307
95.2k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2308
95.2k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2309
95.2k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2310
95.2k
}
2311
2312
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2313
346k
{
2314
346k
    ImU32 out;
2315
346k
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2316
346k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2317
346k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2318
346k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2319
346k
    return out;
2320
346k
}
2321
2322
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2323
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2324
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2325
0
{
2326
0
    float K = 0.f;
2327
0
    if (g < b)
2328
0
    {
2329
0
        ImSwap(g, b);
2330
0
        K = -1.f;
2331
0
    }
2332
0
    if (r < g)
2333
0
    {
2334
0
        ImSwap(r, g);
2335
0
        K = -2.f / 6.f - K;
2336
0
    }
2337
2338
0
    const float chroma = r - (g < b ? g : b);
2339
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2340
0
    out_s = chroma / (r + 1e-20f);
2341
0
    out_v = r;
2342
0
}
2343
2344
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2345
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2346
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2347
0
{
2348
0
    if (s == 0.0f)
2349
0
    {
2350
        // gray
2351
0
        out_r = out_g = out_b = v;
2352
0
        return;
2353
0
    }
2354
2355
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2356
0
    int   i = (int)h;
2357
0
    float f = h - (float)i;
2358
0
    float p = v * (1.0f - s);
2359
0
    float q = v * (1.0f - s * f);
2360
0
    float t = v * (1.0f - s * (1.0f - f));
2361
2362
0
    switch (i)
2363
0
    {
2364
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2365
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2366
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2367
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2368
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2369
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2370
0
    }
2371
0
}
2372
2373
//-----------------------------------------------------------------------------
2374
// [SECTION] ImGuiStorage
2375
// Helper: Key->value storage
2376
//-----------------------------------------------------------------------------
2377
2378
// std::lower_bound but without the bullshit
2379
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2380
45.5k
{
2381
45.5k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2382
45.5k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2383
45.5k
    size_t count = (size_t)(last - first);
2384
136k
    while (count > 0)
2385
91.0k
    {
2386
91.0k
        size_t count2 = count >> 1;
2387
91.0k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2388
91.0k
        if (mid->key < key)
2389
27.5k
        {
2390
27.5k
            first = ++mid;
2391
27.5k
            count -= count2 + 1;
2392
27.5k
        }
2393
63.5k
        else
2394
63.5k
        {
2395
63.5k
            count = count2;
2396
63.5k
        }
2397
91.0k
    }
2398
45.5k
    return first;
2399
45.5k
}
2400
2401
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2402
void ImGuiStorage::BuildSortByKey()
2403
0
{
2404
0
    struct StaticFunc
2405
0
    {
2406
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2407
0
        {
2408
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2409
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2410
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2411
0
            return 0;
2412
0
        }
2413
0
    };
2414
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2415
0
}
2416
2417
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2418
0
{
2419
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2420
0
    if (it == Data.end() || it->key != key)
2421
0
        return default_val;
2422
0
    return it->val_i;
2423
0
}
2424
2425
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2426
0
{
2427
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2428
0
}
2429
2430
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2431
0
{
2432
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2433
0
    if (it == Data.end() || it->key != key)
2434
0
        return default_val;
2435
0
    return it->val_f;
2436
0
}
2437
2438
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2439
45.5k
{
2440
45.5k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2441
45.5k
    if (it == Data.end() || it->key != key)
2442
3
        return NULL;
2443
45.5k
    return it->val_p;
2444
45.5k
}
2445
2446
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2447
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2448
0
{
2449
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2450
0
    if (it == Data.end() || it->key != key)
2451
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2452
0
    return &it->val_i;
2453
0
}
2454
2455
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2456
0
{
2457
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2458
0
}
2459
2460
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2461
0
{
2462
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2463
0
    if (it == Data.end() || it->key != key)
2464
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2465
0
    return &it->val_f;
2466
0
}
2467
2468
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2469
0
{
2470
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2471
0
    if (it == Data.end() || it->key != key)
2472
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2473
0
    return &it->val_p;
2474
0
}
2475
2476
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2477
void ImGuiStorage::SetInt(ImGuiID key, int val)
2478
0
{
2479
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2480
0
    if (it == Data.end() || it->key != key)
2481
0
    {
2482
0
        Data.insert(it, ImGuiStoragePair(key, val));
2483
0
        return;
2484
0
    }
2485
0
    it->val_i = val;
2486
0
}
2487
2488
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2489
0
{
2490
0
    SetInt(key, val ? 1 : 0);
2491
0
}
2492
2493
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2494
0
{
2495
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2496
0
    if (it == Data.end() || it->key != key)
2497
0
    {
2498
0
        Data.insert(it, ImGuiStoragePair(key, val));
2499
0
        return;
2500
0
    }
2501
0
    it->val_f = val;
2502
0
}
2503
2504
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2505
3
{
2506
3
    ImGuiStoragePair* it = LowerBound(Data, key);
2507
3
    if (it == Data.end() || it->key != key)
2508
3
    {
2509
3
        Data.insert(it, ImGuiStoragePair(key, val));
2510
3
        return;
2511
3
    }
2512
0
    it->val_p = val;
2513
0
}
2514
2515
void ImGuiStorage::SetAllInt(int v)
2516
0
{
2517
0
    for (int i = 0; i < Data.Size; i++)
2518
0
        Data[i].val_i = v;
2519
0
}
2520
2521
//-----------------------------------------------------------------------------
2522
// [SECTION] ImGuiTextFilter
2523
//-----------------------------------------------------------------------------
2524
2525
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2526
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2527
0
{
2528
0
    InputBuf[0] = 0;
2529
0
    CountGrep = 0;
2530
0
    if (default_filter)
2531
0
    {
2532
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2533
0
        Build();
2534
0
    }
2535
0
}
2536
2537
bool ImGuiTextFilter::Draw(const char* label, float width)
2538
0
{
2539
0
    if (width != 0.0f)
2540
0
        ImGui::SetNextItemWidth(width);
2541
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2542
0
    if (value_changed)
2543
0
        Build();
2544
0
    return value_changed;
2545
0
}
2546
2547
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2548
0
{
2549
0
    out->resize(0);
2550
0
    const char* wb = b;
2551
0
    const char* we = wb;
2552
0
    while (we < e)
2553
0
    {
2554
0
        if (*we == separator)
2555
0
        {
2556
0
            out->push_back(ImGuiTextRange(wb, we));
2557
0
            wb = we + 1;
2558
0
        }
2559
0
        we++;
2560
0
    }
2561
0
    if (wb != we)
2562
0
        out->push_back(ImGuiTextRange(wb, we));
2563
0
}
2564
2565
void ImGuiTextFilter::Build()
2566
0
{
2567
0
    Filters.resize(0);
2568
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2569
0
    input_range.split(',', &Filters);
2570
2571
0
    CountGrep = 0;
2572
0
    for (int i = 0; i != Filters.Size; i++)
2573
0
    {
2574
0
        ImGuiTextRange& f = Filters[i];
2575
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2576
0
            f.b++;
2577
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2578
0
            f.e--;
2579
0
        if (f.empty())
2580
0
            continue;
2581
0
        if (Filters[i].b[0] != '-')
2582
0
            CountGrep += 1;
2583
0
    }
2584
0
}
2585
2586
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2587
0
{
2588
0
    if (Filters.empty())
2589
0
        return true;
2590
2591
0
    if (text == NULL)
2592
0
        text = "";
2593
2594
0
    for (int i = 0; i != Filters.Size; i++)
2595
0
    {
2596
0
        const ImGuiTextRange& f = Filters[i];
2597
0
        if (f.empty())
2598
0
            continue;
2599
0
        if (f.b[0] == '-')
2600
0
        {
2601
            // Subtract
2602
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2603
0
                return false;
2604
0
        }
2605
0
        else
2606
0
        {
2607
            // Grep
2608
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2609
0
                return true;
2610
0
        }
2611
0
    }
2612
2613
    // Implicit * grep
2614
0
    if (CountGrep == 0)
2615
0
        return true;
2616
2617
0
    return false;
2618
0
}
2619
2620
//-----------------------------------------------------------------------------
2621
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2622
//-----------------------------------------------------------------------------
2623
2624
// On some platform vsnprintf() takes va_list by reference and modifies it.
2625
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2626
#ifndef va_copy
2627
#if defined(__GNUC__) || defined(__clang__)
2628
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2629
#else
2630
#define va_copy(dest, src) (dest = src)
2631
#endif
2632
#endif
2633
2634
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2635
2636
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2637
0
{
2638
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2639
2640
    // Add zero-terminator the first time
2641
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2642
0
    const int needed_sz = write_off + len;
2643
0
    if (write_off + len >= Buf.Capacity)
2644
0
    {
2645
0
        int new_capacity = Buf.Capacity * 2;
2646
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2647
0
    }
2648
2649
0
    Buf.resize(needed_sz);
2650
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2651
0
    Buf[write_off - 1 + len] = 0;
2652
0
}
2653
2654
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2655
0
{
2656
0
    va_list args;
2657
0
    va_start(args, fmt);
2658
0
    appendfv(fmt, args);
2659
0
    va_end(args);
2660
0
}
2661
2662
// Helper: Text buffer for logging/accumulating text
2663
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2664
0
{
2665
0
    va_list args_copy;
2666
0
    va_copy(args_copy, args);
2667
2668
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2669
0
    if (len <= 0)
2670
0
    {
2671
0
        va_end(args_copy);
2672
0
        return;
2673
0
    }
2674
2675
    // Add zero-terminator the first time
2676
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2677
0
    const int needed_sz = write_off + len;
2678
0
    if (write_off + len >= Buf.Capacity)
2679
0
    {
2680
0
        int new_capacity = Buf.Capacity * 2;
2681
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2682
0
    }
2683
2684
0
    Buf.resize(needed_sz);
2685
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2686
0
    va_end(args_copy);
2687
0
}
2688
2689
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2690
0
{
2691
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2692
0
    if (old_size == new_size)
2693
0
        return;
2694
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2695
0
        LineOffsets.push_back(EndOffset);
2696
0
    const char* base_end = base + new_size;
2697
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2698
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2699
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2700
0
    EndOffset = ImMax(EndOffset, new_size);
2701
0
}
2702
2703
//-----------------------------------------------------------------------------
2704
// [SECTION] ImGuiListClipper
2705
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
2706
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
2707
//-----------------------------------------------------------------------------
2708
2709
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2710
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2711
static bool GetSkipItemForListClipping()
2712
0
{
2713
0
    ImGuiContext& g = *GImGui;
2714
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2715
0
}
2716
2717
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2718
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2719
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2720
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2721
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2722
{
2723
    ImGuiContext& g = *GImGui;
2724
    ImGuiWindow* window = g.CurrentWindow;
2725
    if (g.LogEnabled)
2726
    {
2727
        // If logging is active, do not perform any clipping
2728
        *out_items_display_start = 0;
2729
        *out_items_display_end = items_count;
2730
        return;
2731
    }
2732
    if (GetSkipItemForListClipping())
2733
    {
2734
        *out_items_display_start = *out_items_display_end = 0;
2735
        return;
2736
    }
2737
2738
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2739
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2740
    ImRect rect = window->ClipRect;
2741
    if (g.NavMoveScoringItems)
2742
        rect.Add(g.NavScoringNoClipRect);
2743
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2744
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2745
2746
    const ImVec2 pos = window->DC.CursorPos;
2747
    int start = (int)((rect.Min.y - pos.y) / items_height);
2748
    int end = (int)((rect.Max.y - pos.y) / items_height);
2749
2750
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2751
    // FIXME: Verify this works with tabbing
2752
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2753
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2754
        start--;
2755
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2756
        end++;
2757
2758
    start = ImClamp(start, 0, items_count);
2759
    end = ImClamp(end + 1, start, items_count);
2760
    *out_items_display_start = start;
2761
    *out_items_display_end = end;
2762
}
2763
#endif
2764
2765
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2766
0
{
2767
0
    if (ranges.Size - offset <= 1)
2768
0
        return;
2769
2770
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2771
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2772
0
        for (int i = offset; i < sort_end + offset; ++i)
2773
0
            if (ranges[i].Min > ranges[i + 1].Min)
2774
0
                ImSwap(ranges[i], ranges[i + 1]);
2775
2776
    // Now fuse ranges together as much as possible.
2777
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2778
0
    {
2779
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2780
0
        if (ranges[i - 1].Max < ranges[i].Min)
2781
0
            continue;
2782
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2783
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2784
0
        ranges.erase(ranges.Data + i);
2785
0
        i--;
2786
0
    }
2787
0
}
2788
2789
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2790
0
{
2791
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2792
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2793
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2794
0
    ImGuiContext& g = *GImGui;
2795
0
    ImGuiWindow* window = g.CurrentWindow;
2796
0
    float off_y = pos_y - window->DC.CursorPos.y;
2797
0
    window->DC.CursorPos.y = pos_y;
2798
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2799
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2800
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2801
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2802
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2803
0
    if (ImGuiTable* table = g.CurrentTable)
2804
0
    {
2805
0
        if (table->IsInsideRow)
2806
0
            ImGui::TableEndRow(table);
2807
0
        table->RowPosY2 = window->DC.CursorPos.y;
2808
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2809
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2810
0
        table->RowBgColorCounter += row_increase;
2811
0
    }
2812
0
}
2813
2814
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2815
0
{
2816
    // StartPosY starts from ItemsFrozen hence the subtraction
2817
    // Perform the add and multiply with double to allow seeking through larger ranges
2818
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2819
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2820
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2821
0
}
2822
2823
ImGuiListClipper::ImGuiListClipper()
2824
0
{
2825
0
    memset(this, 0, sizeof(*this));
2826
0
}
2827
2828
ImGuiListClipper::~ImGuiListClipper()
2829
0
{
2830
0
    End();
2831
0
}
2832
2833
void ImGuiListClipper::Begin(int items_count, float items_height)
2834
0
{
2835
0
    if (Ctx == NULL)
2836
0
        Ctx = ImGui::GetCurrentContext();
2837
2838
0
    ImGuiContext& g = *Ctx;
2839
0
    ImGuiWindow* window = g.CurrentWindow;
2840
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2841
2842
0
    if (ImGuiTable* table = g.CurrentTable)
2843
0
        if (table->IsInsideRow)
2844
0
            ImGui::TableEndRow(table);
2845
2846
0
    StartPosY = window->DC.CursorPos.y;
2847
0
    ItemsHeight = items_height;
2848
0
    ItemsCount = items_count;
2849
0
    DisplayStart = -1;
2850
0
    DisplayEnd = 0;
2851
2852
    // Acquire temporary buffer
2853
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2854
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2855
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2856
0
    data->Reset(this);
2857
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2858
0
    TempData = data;
2859
0
}
2860
2861
void ImGuiListClipper::End()
2862
0
{
2863
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2864
0
    {
2865
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2866
0
        ImGuiContext& g = *Ctx;
2867
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2868
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2869
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2870
2871
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2872
0
        IM_ASSERT(data->ListClipper == this);
2873
0
        data->StepNo = data->Ranges.Size;
2874
0
        if (--g.ClipperTempDataStacked > 0)
2875
0
        {
2876
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2877
0
            data->ListClipper->TempData = data;
2878
0
        }
2879
0
        TempData = NULL;
2880
0
    }
2881
0
    ItemsCount = -1;
2882
0
}
2883
2884
void ImGuiListClipper::IncludeRangeByIndices(int item_begin, int item_end)
2885
0
{
2886
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2887
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2888
0
    IM_ASSERT(item_begin <= item_end);
2889
0
    if (item_begin < item_end)
2890
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_begin, item_end));
2891
0
}
2892
2893
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2894
0
{
2895
0
    ImGuiContext& g = *clipper->Ctx;
2896
0
    ImGuiWindow* window = g.CurrentWindow;
2897
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2898
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2899
2900
0
    ImGuiTable* table = g.CurrentTable;
2901
0
    if (table && table->IsInsideRow)
2902
0
        ImGui::TableEndRow(table);
2903
2904
    // No items
2905
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2906
0
        return false;
2907
2908
    // While we are in frozen row state, keep displaying items one by one, unclipped
2909
    // FIXME: Could be stored as a table-agnostic state.
2910
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2911
0
    {
2912
0
        clipper->DisplayStart = data->ItemsFrozen;
2913
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2914
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2915
0
            data->ItemsFrozen++;
2916
0
        return true;
2917
0
    }
2918
2919
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2920
0
    bool calc_clipping = false;
2921
0
    if (data->StepNo == 0)
2922
0
    {
2923
0
        clipper->StartPosY = window->DC.CursorPos.y;
2924
0
        if (clipper->ItemsHeight <= 0.0f)
2925
0
        {
2926
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2927
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2928
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2929
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2930
0
            data->StepNo = 1;
2931
0
            return true;
2932
0
        }
2933
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2934
0
    }
2935
2936
    // Step 1: Let the clipper infer height from first range
2937
0
    if (clipper->ItemsHeight <= 0.0f)
2938
0
    {
2939
0
        IM_ASSERT(data->StepNo == 1);
2940
0
        if (table)
2941
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2942
2943
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2944
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2945
0
        if (affected_by_floating_point_precision)
2946
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2947
2948
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2949
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2950
0
    }
2951
2952
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2953
0
    const int already_submitted = clipper->DisplayEnd;
2954
0
    if (calc_clipping)
2955
0
    {
2956
0
        if (g.LogEnabled)
2957
0
        {
2958
            // If logging is active, do not perform any clipping
2959
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2960
0
        }
2961
0
        else
2962
0
        {
2963
            // Add range selected to be included for navigation
2964
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2965
0
            if (is_nav_request)
2966
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
2967
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
2968
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
2969
2970
            // Add focused/active item
2971
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
2972
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2973
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
2974
2975
            // Add visible range
2976
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
2977
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
2978
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
2979
0
        }
2980
2981
        // Convert position ranges to item index ranges
2982
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
2983
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
2984
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
2985
0
        for (int i = 0; i < data->Ranges.Size; i++)
2986
0
            if (data->Ranges[i].PosToIndexConvert)
2987
0
            {
2988
0
                int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
2989
0
                int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
2990
0
                data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
2991
0
                data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, clipper->ItemsCount);
2992
0
                data->Ranges[i].PosToIndexConvert = false;
2993
0
            }
2994
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
2995
0
    }
2996
2997
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
2998
0
    if (data->StepNo < data->Ranges.Size)
2999
0
    {
3000
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
3001
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
3002
0
        if (clipper->DisplayStart > already_submitted) //-V1051
3003
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
3004
0
        data->StepNo++;
3005
0
        return true;
3006
0
    }
3007
3008
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
3009
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
3010
0
    if (clipper->ItemsCount < INT_MAX)
3011
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
3012
3013
0
    return false;
3014
0
}
3015
3016
bool ImGuiListClipper::Step()
3017
0
{
3018
0
    ImGuiContext& g = *Ctx;
3019
0
    bool need_items_height = (ItemsHeight <= 0.0f);
3020
0
    bool ret = ImGuiListClipper_StepInternal(this);
3021
0
    if (ret && (DisplayStart == DisplayEnd))
3022
0
        ret = false;
3023
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
3024
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
3025
0
    if (need_items_height && ItemsHeight > 0.0f)
3026
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
3027
0
    if (ret)
3028
0
    {
3029
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
3030
0
    }
3031
0
    else
3032
0
    {
3033
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
3034
0
        End();
3035
0
    }
3036
0
    return ret;
3037
0
}
3038
3039
//-----------------------------------------------------------------------------
3040
// [SECTION] STYLING
3041
//-----------------------------------------------------------------------------
3042
3043
ImGuiStyle& ImGui::GetStyle()
3044
77.2k
{
3045
77.2k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
3046
77.2k
    return GImGui->Style;
3047
77.2k
}
3048
3049
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
3050
268k
{
3051
268k
    ImGuiStyle& style = GImGui->Style;
3052
268k
    ImVec4 c = style.Colors[idx];
3053
268k
    c.w *= style.Alpha * alpha_mul;
3054
268k
    return ColorConvertFloat4ToU32(c);
3055
268k
}
3056
3057
ImU32 ImGui::GetColorU32(const ImVec4& col)
3058
0
{
3059
0
    ImGuiStyle& style = GImGui->Style;
3060
0
    ImVec4 c = col;
3061
0
    c.w *= style.Alpha;
3062
0
    return ColorConvertFloat4ToU32(c);
3063
0
}
3064
3065
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3066
0
{
3067
0
    ImGuiStyle& style = GImGui->Style;
3068
0
    return style.Colors[idx];
3069
0
}
3070
3071
ImU32 ImGui::GetColorU32(ImU32 col)
3072
0
{
3073
0
    ImGuiStyle& style = GImGui->Style;
3074
0
    if (style.Alpha >= 1.0f)
3075
0
        return col;
3076
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3077
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3078
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3079
0
}
3080
3081
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3082
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3083
0
{
3084
0
    ImGuiContext& g = *GImGui;
3085
0
    ImGuiColorMod backup;
3086
0
    backup.Col = idx;
3087
0
    backup.BackupValue = g.Style.Colors[idx];
3088
0
    g.ColorStack.push_back(backup);
3089
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3090
0
}
3091
3092
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3093
18.0k
{
3094
18.0k
    ImGuiContext& g = *GImGui;
3095
18.0k
    ImGuiColorMod backup;
3096
18.0k
    backup.Col = idx;
3097
18.0k
    backup.BackupValue = g.Style.Colors[idx];
3098
18.0k
    g.ColorStack.push_back(backup);
3099
18.0k
    g.Style.Colors[idx] = col;
3100
18.0k
}
3101
3102
void ImGui::PopStyleColor(int count)
3103
18.0k
{
3104
18.0k
    ImGuiContext& g = *GImGui;
3105
18.0k
    if (g.ColorStack.Size < count)
3106
0
    {
3107
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3108
0
        count = g.ColorStack.Size;
3109
0
    }
3110
36.0k
    while (count > 0)
3111
18.0k
    {
3112
18.0k
        ImGuiColorMod& backup = g.ColorStack.back();
3113
18.0k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3114
18.0k
        g.ColorStack.pop_back();
3115
18.0k
        count--;
3116
18.0k
    }
3117
18.0k
}
3118
3119
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3120
{
3121
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3122
};
3123
3124
static const ImGuiDataVarInfo GStyleVarInfo[] =
3125
{
3126
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3127
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3128
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3129
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3130
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3131
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3132
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3133
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3134
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3135
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3136
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3137
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3138
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3139
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3140
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3141
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3142
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3143
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3144
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3145
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3146
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3147
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3148
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3149
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3150
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3151
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3152
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextAlign) },     // ImGuiStyleVar_SeparatorTextAlign
3153
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextPadding) },   // ImGuiStyleVar_SeparatorTextPadding
3154
};
3155
3156
const ImGuiDataVarInfo* ImGui::GetStyleVarInfo(ImGuiStyleVar idx)
3157
36.0k
{
3158
36.0k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3159
36.0k
    IM_STATIC_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3160
36.0k
    return &GStyleVarInfo[idx];
3161
36.0k
}
3162
3163
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3164
0
{
3165
0
    ImGuiContext& g = *GImGui;
3166
0
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3167
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3168
0
    {
3169
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3170
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3171
0
        *pvar = val;
3172
0
        return;
3173
0
    }
3174
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3175
0
}
3176
3177
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3178
18.0k
{
3179
18.0k
    ImGuiContext& g = *GImGui;
3180
18.0k
    const ImGuiDataVarInfo* var_info = GetStyleVarInfo(idx);
3181
18.0k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3182
18.0k
    {
3183
18.0k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3184
18.0k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3185
18.0k
        *pvar = val;
3186
18.0k
        return;
3187
18.0k
    }
3188
0
    IM_ASSERT_USER_ERROR(0, "Called PushStyleVar() variant with wrong type!");
3189
0
}
3190
3191
void ImGui::PopStyleVar(int count)
3192
18.0k
{
3193
18.0k
    ImGuiContext& g = *GImGui;
3194
18.0k
    if (g.StyleVarStack.Size < count)
3195
0
    {
3196
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3197
0
        count = g.StyleVarStack.Size;
3198
0
    }
3199
36.0k
    while (count > 0)
3200
18.0k
    {
3201
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3202
18.0k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3203
18.0k
        const ImGuiDataVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3204
18.0k
        void* data = info->GetVarPtr(&g.Style);
3205
18.0k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3206
18.0k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3207
18.0k
        g.StyleVarStack.pop_back();
3208
18.0k
        count--;
3209
18.0k
    }
3210
18.0k
}
3211
3212
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3213
0
{
3214
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3215
0
    switch (idx)
3216
0
    {
3217
0
    case ImGuiCol_Text: return "Text";
3218
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3219
0
    case ImGuiCol_WindowBg: return "WindowBg";
3220
0
    case ImGuiCol_ChildBg: return "ChildBg";
3221
0
    case ImGuiCol_PopupBg: return "PopupBg";
3222
0
    case ImGuiCol_Border: return "Border";
3223
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3224
0
    case ImGuiCol_FrameBg: return "FrameBg";
3225
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3226
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3227
0
    case ImGuiCol_TitleBg: return "TitleBg";
3228
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3229
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3230
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3231
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3232
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3233
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3234
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3235
0
    case ImGuiCol_CheckMark: return "CheckMark";
3236
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3237
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3238
0
    case ImGuiCol_Button: return "Button";
3239
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3240
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3241
0
    case ImGuiCol_Header: return "Header";
3242
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3243
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3244
0
    case ImGuiCol_Separator: return "Separator";
3245
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3246
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3247
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3248
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3249
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3250
0
    case ImGuiCol_Tab: return "Tab";
3251
0
    case ImGuiCol_TabHovered: return "TabHovered";
3252
0
    case ImGuiCol_TabActive: return "TabActive";
3253
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3254
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3255
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3256
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3257
0
    case ImGuiCol_PlotLines: return "PlotLines";
3258
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3259
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3260
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3261
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3262
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3263
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3264
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3265
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3266
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3267
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3268
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3269
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3270
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3271
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3272
0
    }
3273
0
    IM_ASSERT(0);
3274
0
    return "Unknown";
3275
0
}
3276
3277
3278
//-----------------------------------------------------------------------------
3279
// [SECTION] RENDER HELPERS
3280
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3281
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3282
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3283
//-----------------------------------------------------------------------------
3284
3285
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3286
72.0k
{
3287
72.0k
    const char* text_display_end = text;
3288
72.0k
    if (!text_end)
3289
72.0k
        text_end = (const char*)-1;
3290
3291
648k
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3292
576k
        text_display_end++;
3293
72.0k
    return text_display_end;
3294
72.0k
}
3295
3296
// Internal ImGui functions to render text
3297
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3298
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3299
0
{
3300
0
    ImGuiContext& g = *GImGui;
3301
0
    ImGuiWindow* window = g.CurrentWindow;
3302
3303
    // Hide anything after a '##' string
3304
0
    const char* text_display_end;
3305
0
    if (hide_text_after_hash)
3306
0
    {
3307
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3308
0
    }
3309
0
    else
3310
0
    {
3311
0
        if (!text_end)
3312
0
            text_end = text + strlen(text); // FIXME-OPT
3313
0
        text_display_end = text_end;
3314
0
    }
3315
3316
0
    if (text != text_display_end)
3317
0
    {
3318
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3319
0
        if (g.LogEnabled)
3320
0
            LogRenderedText(&pos, text, text_display_end);
3321
0
    }
3322
0
}
3323
3324
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3325
0
{
3326
0
    ImGuiContext& g = *GImGui;
3327
0
    ImGuiWindow* window = g.CurrentWindow;
3328
3329
0
    if (!text_end)
3330
0
        text_end = text + strlen(text); // FIXME-OPT
3331
3332
0
    if (text != text_end)
3333
0
    {
3334
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3335
0
        if (g.LogEnabled)
3336
0
            LogRenderedText(&pos, text, text_end);
3337
0
    }
3338
0
}
3339
3340
// Default clip_rect uses (pos_min,pos_max)
3341
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3342
// FIXME-OPT: Since we have or calculate text_size we could coarse clip whole block immediately, especally for text above draw_list->DrawList.
3343
// Effectively as this is called from widget doing their own coarse clipping it's not very valuable presently. Next time function will take
3344
// better advantage of the render function taking size into account for coarse clipping.
3345
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3346
36.0k
{
3347
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3348
36.0k
    ImVec2 pos = pos_min;
3349
36.0k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3350
3351
36.0k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3352
36.0k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3353
36.0k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3354
36.0k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3355
36.0k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3356
3357
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3358
36.0k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3359
36.0k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3360
3361
    // Render
3362
36.0k
    if (need_clipping)
3363
18.0k
    {
3364
18.0k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3365
18.0k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3366
18.0k
    }
3367
18.0k
    else
3368
18.0k
    {
3369
18.0k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3370
18.0k
    }
3371
36.0k
}
3372
3373
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3374
36.0k
{
3375
    // Hide anything after a '##' string
3376
36.0k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3377
36.0k
    const int text_len = (int)(text_display_end - text);
3378
36.0k
    if (text_len == 0)
3379
0
        return;
3380
3381
36.0k
    ImGuiContext& g = *GImGui;
3382
36.0k
    ImGuiWindow* window = g.CurrentWindow;
3383
36.0k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3384
36.0k
    if (g.LogEnabled)
3385
0
        LogRenderedText(&pos_min, text, text_display_end);
3386
36.0k
}
3387
3388
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3389
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3390
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3391
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3392
0
{
3393
0
    ImGuiContext& g = *GImGui;
3394
0
    if (text_end_full == NULL)
3395
0
        text_end_full = FindRenderedTextEnd(text);
3396
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3397
3398
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3399
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3400
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3401
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3402
0
    if (text_size.x > pos_max.x - pos_min.x)
3403
0
    {
3404
        // Hello wo...
3405
        // |       |   |
3406
        // min   max   ellipsis_max
3407
        //          <-> this is generally some padding value
3408
3409
0
        const ImFont* font = draw_list->_Data->Font;
3410
0
        const float font_size = draw_list->_Data->FontSize;
3411
0
        const float font_scale = font_size / font->FontSize;
3412
0
        const char* text_end_ellipsis = NULL;
3413
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3414
3415
        // We can now claim the space between pos_max.x and ellipsis_max.x
3416
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3417
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3418
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3419
0
        {
3420
            // Always display at least 1 character if there's no room for character + ellipsis
3421
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3422
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3423
0
        }
3424
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3425
0
        {
3426
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3427
0
            text_end_ellipsis--;
3428
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3429
0
        }
3430
3431
        // Render text, render ellipsis
3432
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3433
0
        ImVec2 ellipsis_pos = ImFloor(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3434
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3435
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3436
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3437
0
    }
3438
0
    else
3439
0
    {
3440
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3441
0
    }
3442
3443
0
    if (g.LogEnabled)
3444
0
        LogRenderedText(&pos_min, text, text_end_full);
3445
0
}
3446
3447
// Render a rectangle shaped with optional rounding and borders
3448
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3449
8.49k
{
3450
8.49k
    ImGuiContext& g = *GImGui;
3451
8.49k
    ImGuiWindow* window = g.CurrentWindow;
3452
8.49k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3453
8.49k
    const float border_size = g.Style.FrameBorderSize;
3454
8.49k
    if (border && border_size > 0.0f)
3455
8.49k
    {
3456
8.49k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3457
8.49k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3458
8.49k
    }
3459
8.49k
}
3460
3461
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3462
0
{
3463
0
    ImGuiContext& g = *GImGui;
3464
0
    ImGuiWindow* window = g.CurrentWindow;
3465
0
    const float border_size = g.Style.FrameBorderSize;
3466
0
    if (border_size > 0.0f)
3467
0
    {
3468
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3469
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3470
0
    }
3471
0
}
3472
3473
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3474
15.7k
{
3475
15.7k
    ImGuiContext& g = *GImGui;
3476
15.7k
    if (id != g.NavId)
3477
8.51k
        return;
3478
7.19k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3479
1.55k
        return;
3480
5.63k
    ImGuiWindow* window = g.CurrentWindow;
3481
5.63k
    if (window->DC.NavHideHighlightOneFrame)
3482
0
        return;
3483
3484
5.63k
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3485
5.63k
    ImRect display_rect = bb;
3486
5.63k
    display_rect.ClipWith(window->ClipRect);
3487
5.63k
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3488
147
    {
3489
147
        const float THICKNESS = 2.0f;
3490
147
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3491
147
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3492
147
        bool fully_visible = window->ClipRect.Contains(display_rect);
3493
147
        if (!fully_visible)
3494
144
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3495
147
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3496
147
        if (!fully_visible)
3497
144
            window->DrawList->PopClipRect();
3498
147
    }
3499
5.63k
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3500
5.49k
    {
3501
5.49k
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3502
5.49k
    }
3503
5.63k
}
3504
3505
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3506
0
{
3507
0
    ImGuiContext& g = *GImGui;
3508
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3509
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3510
0
    for (int n = 0; n < g.Viewports.Size; n++)
3511
0
    {
3512
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3513
0
        ImVec2 offset, size, uv[4];
3514
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3515
0
            continue;
3516
0
        ImGuiViewportP* viewport = g.Viewports[n];
3517
0
        const ImVec2 pos = base_pos - offset;
3518
0
        const float scale = base_scale * viewport->DpiScale;
3519
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3520
0
            continue;
3521
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3522
0
        ImTextureID tex_id = font_atlas->TexID;
3523
0
        draw_list->PushTextureID(tex_id);
3524
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3525
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3526
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3527
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3528
0
        draw_list->PopTextureID();
3529
0
    }
3530
0
}
3531
3532
//-----------------------------------------------------------------------------
3533
// [SECTION] INITIALIZATION, SHUTDOWN
3534
//-----------------------------------------------------------------------------
3535
3536
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3537
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3538
ImGuiContext* ImGui::GetCurrentContext()
3539
1
{
3540
1
    return GImGui;
3541
1
}
3542
3543
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3544
1
{
3545
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3546
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3547
#else
3548
1
    GImGui = ctx;
3549
1
#endif
3550
1
}
3551
3552
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3553
0
{
3554
0
    GImAllocatorAllocFunc = alloc_func;
3555
0
    GImAllocatorFreeFunc = free_func;
3556
0
    GImAllocatorUserData = user_data;
3557
0
}
3558
3559
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3560
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3561
0
{
3562
0
    *p_alloc_func = GImAllocatorAllocFunc;
3563
0
    *p_free_func = GImAllocatorFreeFunc;
3564
0
    *p_user_data = GImAllocatorUserData;
3565
0
}
3566
3567
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3568
1
{
3569
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3570
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3571
1
    SetCurrentContext(ctx);
3572
1
    Initialize();
3573
1
    if (prev_ctx != NULL)
3574
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3575
1
    return ctx;
3576
1
}
3577
3578
void ImGui::DestroyContext(ImGuiContext* ctx)
3579
0
{
3580
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3581
0
    if (ctx == NULL) //-V1051
3582
0
        ctx = prev_ctx;
3583
0
    SetCurrentContext(ctx);
3584
0
    Shutdown();
3585
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3586
0
    IM_DELETE(ctx);
3587
0
}
3588
3589
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3590
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3591
{
3592
    { ImGuiLocKey_VersionStr,           "Dear ImGui " IMGUI_VERSION " (" IM_STRINGIFY(IMGUI_VERSION_NUM) ")" },
3593
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3594
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3595
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3596
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3597
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3598
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3599
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3600
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3601
};
3602
3603
void ImGui::Initialize()
3604
1
{
3605
1
    ImGuiContext& g = *GImGui;
3606
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3607
3608
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3609
1
    {
3610
1
        ImGuiSettingsHandler ini_handler;
3611
1
        ini_handler.TypeName = "Window";
3612
1
        ini_handler.TypeHash = ImHashStr("Window");
3613
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3614
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3615
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3616
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3617
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3618
1
        AddSettingsHandler(&ini_handler);
3619
1
    }
3620
1
    TableSettingsAddSettingsHandler();
3621
3622
    // Setup default localization table
3623
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3624
3625
    // Setup default platform clipboard/IME handlers.
3626
1
    g.IO.GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;    // Platform dependent default implementations
3627
1
    g.IO.SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
3628
1
    g.IO.ClipboardUserData = (void*)&g;                          // Default implementation use the ImGuiContext as user data (ideally those would be arguments to the function)
3629
1
    g.IO.SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
3630
3631
    // Create default viewport
3632
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3633
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3634
1
    viewport->Idx = 0;
3635
1
    viewport->PlatformWindowCreated = true;
3636
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3637
1
    g.Viewports.push_back(viewport);
3638
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3639
1
    g.ViewportCreatedCount++;
3640
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3641
3642
1
#ifdef IMGUI_HAS_DOCK
3643
    // Initialize Docking
3644
1
    DockContextInitialize(&g);
3645
1
#endif
3646
3647
1
    g.Initialized = true;
3648
1
}
3649
3650
// This function is merely here to free heap allocations.
3651
void ImGui::Shutdown()
3652
0
{
3653
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3654
0
    ImGuiContext& g = *GImGui;
3655
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3656
0
    {
3657
0
        g.IO.Fonts->Locked = false;
3658
0
        IM_DELETE(g.IO.Fonts);
3659
0
    }
3660
0
    g.IO.Fonts = NULL;
3661
0
    g.DrawListSharedData.TempBuffer.clear();
3662
3663
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3664
0
    if (!g.Initialized)
3665
0
        return;
3666
3667
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3668
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3669
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3670
3671
    // Destroy platform windows
3672
0
    DestroyPlatformWindows();
3673
3674
    // Shutdown extensions
3675
0
    DockContextShutdown(&g);
3676
3677
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3678
3679
    // Clear everything else
3680
0
    g.Windows.clear_delete();
3681
0
    g.WindowsFocusOrder.clear();
3682
0
    g.WindowsTempSortBuffer.clear();
3683
0
    g.CurrentWindow = NULL;
3684
0
    g.CurrentWindowStack.clear();
3685
0
    g.WindowsById.Clear();
3686
0
    g.NavWindow = NULL;
3687
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3688
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3689
0
    g.MovingWindow = NULL;
3690
3691
0
    g.KeysRoutingTable.Clear();
3692
3693
0
    g.ColorStack.clear();
3694
0
    g.StyleVarStack.clear();
3695
0
    g.FontStack.clear();
3696
0
    g.OpenPopupStack.clear();
3697
0
    g.BeginPopupStack.clear();
3698
3699
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3700
0
    g.Viewports.clear_delete();
3701
3702
0
    g.TabBars.Clear();
3703
0
    g.CurrentTabBarStack.clear();
3704
0
    g.ShrinkWidthBuffer.clear();
3705
3706
0
    g.ClipperTempData.clear_destruct();
3707
3708
0
    g.Tables.Clear();
3709
0
    g.TablesTempData.clear_destruct();
3710
0
    g.DrawChannelsTempMergeBuffer.clear();
3711
3712
0
    g.ClipboardHandlerData.clear();
3713
0
    g.MenusIdSubmittedThisFrame.clear();
3714
0
    g.InputTextState.ClearFreeMemory();
3715
0
    g.InputTextDeactivatedState.ClearFreeMemory();
3716
3717
0
    g.SettingsWindows.clear();
3718
0
    g.SettingsHandlers.clear();
3719
3720
0
    if (g.LogFile)
3721
0
    {
3722
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3723
0
        if (g.LogFile != stdout)
3724
0
#endif
3725
0
            ImFileClose(g.LogFile);
3726
0
        g.LogFile = NULL;
3727
0
    }
3728
0
    g.LogBuffer.clear();
3729
0
    g.DebugLogBuf.clear();
3730
0
    g.DebugLogIndex.clear();
3731
3732
0
    g.Initialized = false;
3733
0
}
3734
3735
// No specific ordering/dependency support, will see as needed
3736
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3737
0
{
3738
0
    ImGuiContext& g = *ctx;
3739
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3740
0
    g.Hooks.push_back(*hook);
3741
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3742
0
    return g.HookIdNext;
3743
0
}
3744
3745
// Deferred removal, avoiding issue with changing vector while iterating it
3746
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3747
0
{
3748
0
    ImGuiContext& g = *ctx;
3749
0
    IM_ASSERT(hook_id != 0);
3750
0
    for (int n = 0; n < g.Hooks.Size; n++)
3751
0
        if (g.Hooks[n].HookId == hook_id)
3752
0
            g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
3753
0
}
3754
3755
// Call context hooks (used by e.g. test engine)
3756
// We assume a small number of hooks so all stored in same array
3757
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3758
108k
{
3759
108k
    ImGuiContext& g = *ctx;
3760
108k
    for (int n = 0; n < g.Hooks.Size; n++)
3761
0
        if (g.Hooks[n].Type == hook_type)
3762
0
            g.Hooks[n].Callback(&g, &g.Hooks[n]);
3763
108k
}
3764
3765
3766
//-----------------------------------------------------------------------------
3767
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3768
//-----------------------------------------------------------------------------
3769
3770
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3771
ImGuiWindow::ImGuiWindow(ImGuiContext* ctx, const char* name) : DrawListInst(NULL)
3772
3
{
3773
3
    memset(this, 0, sizeof(*this));
3774
3
    Ctx = ctx;
3775
3
    Name = ImStrdup(name);
3776
3
    NameBufLen = (int)strlen(name) + 1;
3777
3
    ID = ImHashStr(name);
3778
3
    IDStack.push_back(ID);
3779
3
    ViewportAllowPlatformMonitorExtend = -1;
3780
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3781
3
    MoveId = GetID("#MOVE");
3782
3
    TabId = GetID("#TAB");
3783
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3784
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3785
3
    AutoFitFramesX = AutoFitFramesY = -1;
3786
3
    AutoPosLastDirection = ImGuiDir_None;
3787
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3788
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3789
3
    LastFrameActive = -1;
3790
3
    LastFrameJustFocused = -1;
3791
3
    LastTimeActive = -1.0f;
3792
3
    FontWindowScale = FontDpiScale = 1.0f;
3793
3
    SettingsOffset = -1;
3794
3
    DockOrder = -1;
3795
3
    DrawList = &DrawListInst;
3796
3
    DrawList->_Data = &Ctx->DrawListSharedData;
3797
3
    DrawList->_OwnerName = Name;
3798
3
    NavPreferredScoringPosRel[0] = NavPreferredScoringPosRel[1] = ImVec2(FLT_MAX, FLT_MAX);
3799
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3800
3
}
3801
3802
ImGuiWindow::~ImGuiWindow()
3803
0
{
3804
0
    IM_ASSERT(DrawList == &DrawListInst);
3805
0
    IM_DELETE(Name);
3806
0
    ColumnsStorage.clear_destruct();
3807
0
}
3808
3809
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3810
82.7k
{
3811
82.7k
    ImGuiID seed = IDStack.back();
3812
82.7k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3813
82.7k
    ImGuiContext& g = *Ctx;
3814
82.7k
    if (g.DebugHookIdInfo == id)
3815
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3816
82.7k
    return id;
3817
82.7k
}
3818
3819
ImGuiID ImGuiWindow::GetID(const void* ptr)
3820
0
{
3821
0
    ImGuiID seed = IDStack.back();
3822
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3823
0
    ImGuiContext& g = *Ctx;
3824
0
    if (g.DebugHookIdInfo == id)
3825
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3826
0
    return id;
3827
0
}
3828
3829
ImGuiID ImGuiWindow::GetID(int n)
3830
9.51k
{
3831
9.51k
    ImGuiID seed = IDStack.back();
3832
9.51k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3833
9.51k
    ImGuiContext& g = *Ctx;
3834
9.51k
    if (g.DebugHookIdInfo == id)
3835
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3836
9.51k
    return id;
3837
9.51k
}
3838
3839
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3840
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3841
0
{
3842
0
    ImGuiID seed = IDStack.back();
3843
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3844
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3845
0
    return id;
3846
0
}
3847
3848
static void SetCurrentWindow(ImGuiWindow* window)
3849
91.0k
{
3850
91.0k
    ImGuiContext& g = *GImGui;
3851
91.0k
    g.CurrentWindow = window;
3852
91.0k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3853
91.0k
    if (window)
3854
73.0k
    {
3855
73.0k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3856
73.0k
        ImGui::NavUpdateCurrentWindowIsScrollPushableX();
3857
73.0k
    }
3858
91.0k
}
3859
3860
void ImGui::GcCompactTransientMiscBuffers()
3861
0
{
3862
0
    ImGuiContext& g = *GImGui;
3863
0
    g.ItemFlagsStack.clear();
3864
0
    g.GroupStack.clear();
3865
0
    TableGcCompactSettings();
3866
0
}
3867
3868
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3869
// Not freed:
3870
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3871
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3872
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3873
1
{
3874
1
    window->MemoryCompacted = true;
3875
1
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3876
1
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3877
1
    window->IDStack.clear();
3878
1
    window->DrawList->_ClearFreeMemory();
3879
1
    window->DC.ChildWindows.clear();
3880
1
    window->DC.ItemWidthStack.clear();
3881
1
    window->DC.TextWrapPosStack.clear();
3882
1
}
3883
3884
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3885
0
{
3886
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3887
    // The other buffers tends to amortize much faster.
3888
0
    window->MemoryCompacted = false;
3889
0
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3890
0
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3891
0
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3892
0
}
3893
3894
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3895
143
{
3896
143
    ImGuiContext& g = *GImGui;
3897
3898
    // Clear previous active id
3899
143
    if (g.ActiveId != 0)
3900
69
    {
3901
        // While most behaved code would make an effort to not steal active id during window move/drag operations,
3902
        // we at least need to be resilient to it. Canceling the move is rather aggressive and users of 'master' branch
3903
        // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3904
69
        if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3905
0
        {
3906
0
            IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3907
0
            g.MovingWindow = NULL;
3908
0
        }
3909
3910
        // This could be written in a more general way (e.g associate a hook to ActiveId),
3911
        // but since this is currently quite an exception we'll leave it as is.
3912
        // One common scenario leading to this is: pressing Key ->NavMoveRequestApplyResult() -> ClearActiveId()
3913
69
        if (g.InputTextState.ID == g.ActiveId)
3914
0
            InputTextDeactivateHook(g.ActiveId);
3915
69
    }
3916
3917
    // Set active id
3918
143
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3919
143
    if (g.ActiveIdIsJustActivated)
3920
135
    {
3921
135
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3922
135
        g.ActiveIdTimer = 0.0f;
3923
135
        g.ActiveIdHasBeenPressedBefore = false;
3924
135
        g.ActiveIdHasBeenEditedBefore = false;
3925
135
        g.ActiveIdMouseButton = -1;
3926
135
        if (id != 0)
3927
69
        {
3928
69
            g.LastActiveId = id;
3929
69
            g.LastActiveIdTimer = 0.0f;
3930
69
        }
3931
135
    }
3932
143
    g.ActiveId = id;
3933
143
    g.ActiveIdAllowOverlap = false;
3934
143
    g.ActiveIdNoClearOnFocusLoss = false;
3935
143
    g.ActiveIdWindow = window;
3936
143
    g.ActiveIdHasBeenEditedThisFrame = false;
3937
143
    if (id)
3938
69
    {
3939
69
        g.ActiveIdIsAlive = id;
3940
69
        g.ActiveIdSource = (g.NavActivateId == id || g.NavJustMovedToId == id) ? g.NavInputSource : ImGuiInputSource_Mouse;
3941
69
        IM_ASSERT(g.ActiveIdSource != ImGuiInputSource_None);
3942
69
    }
3943
3944
    // Clear declaration of inputs claimed by the widget
3945
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3946
143
    g.ActiveIdUsingNavDirMask = 0x00;
3947
143
    g.ActiveIdUsingAllKeyboardKeys = false;
3948
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3949
    g.ActiveIdUsingNavInputMask = 0x00;
3950
#endif
3951
143
}
3952
3953
void ImGui::ClearActiveID()
3954
74
{
3955
74
    SetActiveID(0, NULL); // g.ActiveId = 0;
3956
74
}
3957
3958
void ImGui::SetHoveredID(ImGuiID id)
3959
287
{
3960
287
    ImGuiContext& g = *GImGui;
3961
287
    g.HoveredId = id;
3962
287
    g.HoveredIdAllowOverlap = false;
3963
287
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3964
61
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3965
287
}
3966
3967
ImGuiID ImGui::GetHoveredID()
3968
0
{
3969
0
    ImGuiContext& g = *GImGui;
3970
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3971
0
}
3972
3973
// This is called by ItemAdd().
3974
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
3975
void ImGui::KeepAliveID(ImGuiID id)
3976
65.7k
{
3977
65.7k
    ImGuiContext& g = *GImGui;
3978
65.7k
    if (g.ActiveId == id)
3979
136
        g.ActiveIdIsAlive = id;
3980
65.7k
    if (g.ActiveIdPreviousFrame == id)
3981
133
        g.ActiveIdPreviousFrameIsAlive = true;
3982
65.7k
}
3983
3984
void ImGui::MarkItemEdited(ImGuiID id)
3985
0
{
3986
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
3987
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
3988
0
    ImGuiContext& g = *GImGui;
3989
0
    if (g.ActiveId == id || g.ActiveId == 0)
3990
0
    {
3991
0
        g.ActiveIdHasBeenEditedThisFrame = true;
3992
0
        g.ActiveIdHasBeenEditedBefore = true;
3993
0
    }
3994
3995
    // We accept a MarkItemEdited() on drag and drop targets (see https://github.com/ocornut/imgui/issues/1875#issuecomment-978243343)
3996
    // We accept 'ActiveIdPreviousFrame == id' for InputText() returning an edit after it has been taken ActiveId away (#4714)
3997
0
    IM_ASSERT(g.DragDropActive || g.ActiveId == id || g.ActiveId == 0 || g.ActiveIdPreviousFrame == id);
3998
3999
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
4000
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
4001
0
}
4002
4003
bool ImGui::IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
4004
288
{
4005
    // An active popup disable hovering on other windows (apart from its own children)
4006
    // FIXME-OPT: This could be cached/stored within the window.
4007
288
    ImGuiContext& g = *GImGui;
4008
288
    if (g.NavWindow)
4009
192
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
4010
192
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
4011
0
            {
4012
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
4013
                // NB: The 'else' is important because Modal windows are also Popups.
4014
0
                bool want_inhibit = false;
4015
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
4016
0
                    want_inhibit = true;
4017
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
4018
0
                    want_inhibit = true;
4019
4020
                // Inhibit hover unless the window is within the stack of our modal/popup
4021
0
                if (want_inhibit)
4022
0
                    if (!IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
4023
0
                        return false;
4024
0
            }
4025
4026
    // Filter by viewport
4027
288
    if (window->Viewport != g.MouseViewport)
4028
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
4029
0
            return false;
4030
4031
288
    return true;
4032
288
}
4033
4034
static inline float CalcDelayFromHoveredFlags(ImGuiHoveredFlags flags)
4035
0
{
4036
0
    ImGuiContext& g = *GImGui;
4037
0
    if (flags & ImGuiHoveredFlags_DelayShort)
4038
0
        return g.Style.HoverDelayShort;
4039
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4040
0
        return g.Style.HoverDelayNormal;
4041
0
    return 0.0f;
4042
0
}
4043
4044
// This is roughly matching the behavior of internal-facing ItemHoverable()
4045
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
4046
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
4047
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
4048
0
{
4049
0
    ImGuiContext& g = *GImGui;
4050
0
    ImGuiWindow* window = g.CurrentWindow;
4051
0
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsItemHovered) == 0 && "Invalid flags for IsItemHovered()!");
4052
4053
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
4054
0
    {
4055
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4056
0
            return false;
4057
0
        if (!IsItemFocused())
4058
0
            return false;
4059
4060
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4061
0
            flags |= g.Style.HoverFlagsForTooltipNav;
4062
0
    }
4063
0
    else
4064
0
    {
4065
        // Test for bounding box overlap, as updated as ItemAdd()
4066
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
4067
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
4068
0
            return false;
4069
4070
0
        if (flags & ImGuiHoveredFlags_ForTooltip)
4071
0
            flags |= g.Style.HoverFlagsForTooltipMouse;
4072
4073
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
4074
4075
        // Done with rectangle culling so we can perform heavier checks now
4076
        // Test if we are hovering the right window (our window could be behind another window)
4077
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
4078
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
4079
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
4080
        // the test that has been running for a long while.
4081
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
4082
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByWindow) == 0)
4083
0
                return false;
4084
4085
        // Test if another item is active (e.g. being dragged)
4086
0
        const ImGuiID id = g.LastItemData.ID;
4087
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
4088
0
            if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4089
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
4090
0
                    return false;
4091
4092
        // Test if interactions on this window are blocked by an active popup or modal.
4093
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
4094
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
4095
0
            return false;
4096
4097
        // Test if the item is disabled
4098
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
4099
0
            return false;
4100
4101
        // Special handling for calling after Begin() which represent the title bar or tab.
4102
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
4103
        // will never be overwritten so we need to detect the case.
4104
0
        if (id == window->MoveId && window->WriteAccessed)
4105
0
            return false;
4106
4107
        // Test if using AllowOverlap and overlapped
4108
0
        if ((g.LastItemData.InFlags & ImGuiItemflags_AllowOverlap) && id != 0)
4109
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlappedByItem) == 0)
4110
0
                if (g.HoveredIdPreviousFrame != g.LastItemData.ID)
4111
0
                    return false;
4112
0
    }
4113
4114
    // Handle hover delay
4115
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
4116
0
    const float delay = CalcDelayFromHoveredFlags(flags);
4117
0
    if (delay > 0.0f || (flags & ImGuiHoveredFlags_Stationary))
4118
0
    {
4119
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4120
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverItemDelayIdPreviousFrame != hover_delay_id))
4121
0
            g.HoverItemDelayTimer = 0.0f;
4122
0
        g.HoverItemDelayId = hover_delay_id;
4123
4124
        // When changing hovered item we requires a bit of stationary delay before activating hover timer,
4125
        // but once unlocked on a given item we also moving.
4126
        //if (g.HoverDelayTimer >= delay && (g.HoverDelayTimer - g.IO.DeltaTime < delay || g.MouseStationaryTimer - g.IO.DeltaTime < g.Style.HoverStationaryDelay)) { IMGUI_DEBUG_LOG("HoverDelayTimer = %f/%f, MouseStationaryTimer = %f\n", g.HoverDelayTimer, delay, g.MouseStationaryTimer); }
4127
0
        if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverItemUnlockedStationaryId != hover_delay_id)
4128
0
            return false;
4129
4130
0
        if (g.HoverItemDelayTimer < delay)
4131
0
            return false;
4132
0
    }
4133
4134
0
    return true;
4135
0
}
4136
4137
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4138
// (this does not rely on LastItemData it can be called from a ButtonBehavior() call not following an ItemAdd() call)
4139
// FIXME-LEGACY: the 'ImGuiItemFlags item_flags' parameter was added on 2023-06-28.
4140
// If you used this ii your legacy/custom widgets code:
4141
// - Commonly: if your ItemHoverable() call comes after an ItemAdd() call: pass 'item_flags = g.LastItemData.InFlags'.
4142
// - Rare: otherwise you may pass 'item_flags = 0' (ImGuiItemFlags_None) unless you want to benefit from special behavior handled by ItemHoverable.
4143
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id, ImGuiItemFlags item_flags)
4144
57.0k
{
4145
57.0k
    ImGuiContext& g = *GImGui;
4146
57.0k
    ImGuiWindow* window = g.CurrentWindow;
4147
57.0k
    if (g.HoveredWindow != window)
4148
56.0k
        return false;
4149
1.01k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4150
730
        return false;
4151
4152
288
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4153
0
        return false;
4154
288
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4155
1
        return false;
4156
4157
    // Done with rectangle culling so we can perform heavier checks now.
4158
287
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4159
0
    {
4160
0
        g.HoveredIdDisabled = true;
4161
0
        return false;
4162
0
    }
4163
4164
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4165
    // hover test in widgets code. We could also decide to split this function is two.
4166
287
    if (id != 0)
4167
287
    {
4168
        // Drag source doesn't report as hovered
4169
287
        if (g.DragDropActive && g.DragDropPayload.SourceId == id && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoDisableHover))
4170
0
            return false;
4171
4172
287
        SetHoveredID(id);
4173
4174
        // AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match.
4175
        // This allows using patterns where a later submitted widget overlaps a previous one. Generally perceived as a front-to-back hit-test.
4176
287
        if (item_flags & ImGuiItemflags_AllowOverlap)
4177
0
        {
4178
0
            g.HoveredIdAllowOverlap = true;
4179
0
            if (g.HoveredIdPreviousFrame != id)
4180
0
                return false;
4181
0
        }
4182
287
    }
4183
4184
    // When disabled we'll return false but still set HoveredId
4185
287
    if (item_flags & ImGuiItemFlags_Disabled)
4186
0
    {
4187
        // Release active id if turning disabled
4188
0
        if (g.ActiveId == id && id != 0)
4189
0
            ClearActiveID();
4190
0
        g.HoveredIdDisabled = true;
4191
0
        return false;
4192
0
    }
4193
4194
287
    if (id != 0)
4195
287
    {
4196
        // [DEBUG] Item Picker tool!
4197
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4198
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4199
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4200
287
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4201
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4202
287
        if (g.DebugItemPickerBreakId == id)
4203
0
            IM_DEBUG_BREAK();
4204
287
    }
4205
4206
287
    if (g.NavDisableMouseHover)
4207
7
        return false;
4208
4209
280
    return true;
4210
287
}
4211
4212
// FIXME: This is inlined/duplicated in ItemAdd()
4213
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4214
0
{
4215
0
    ImGuiContext& g = *GImGui;
4216
0
    ImGuiWindow* window = g.CurrentWindow;
4217
0
    if (!bb.Overlaps(window->ClipRect))
4218
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4219
0
            if (!g.LogEnabled)
4220
0
                return true;
4221
0
    return false;
4222
0
}
4223
4224
// This is also inlined in ItemAdd()
4225
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set g.LastItemData.DisplayRect.
4226
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4227
45.5k
{
4228
45.5k
    ImGuiContext& g = *GImGui;
4229
45.5k
    g.LastItemData.ID = item_id;
4230
45.5k
    g.LastItemData.InFlags = in_flags;
4231
45.5k
    g.LastItemData.StatusFlags = item_flags;
4232
45.5k
    g.LastItemData.Rect = g.LastItemData.NavRect = item_rect;
4233
45.5k
}
4234
4235
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4236
0
{
4237
0
    if (wrap_pos_x < 0.0f)
4238
0
        return 0.0f;
4239
4240
0
    ImGuiContext& g = *GImGui;
4241
0
    ImGuiWindow* window = g.CurrentWindow;
4242
0
    if (wrap_pos_x == 0.0f)
4243
0
    {
4244
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4245
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4246
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4247
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4248
        //else
4249
0
        wrap_pos_x = window->WorkRect.Max.x;
4250
0
    }
4251
0
    else if (wrap_pos_x > 0.0f)
4252
0
    {
4253
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4254
0
    }
4255
4256
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4257
0
}
4258
4259
// IM_ALLOC() == ImGui::MemAlloc()
4260
void* ImGui::MemAlloc(size_t size)
4261
1.22k
{
4262
1.22k
    if (ImGuiContext* ctx = GImGui)
4263
1.21k
        ctx->IO.MetricsActiveAllocations++;
4264
1.22k
    return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4265
1.22k
}
4266
4267
// IM_FREE() == ImGui::MemFree()
4268
void ImGui::MemFree(void* ptr)
4269
1.17k
{
4270
1.17k
    if (ptr)
4271
1.16k
        if (ImGuiContext* ctx = GImGui)
4272
1.16k
            ctx->IO.MetricsActiveAllocations--;
4273
1.17k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4274
1.17k
}
4275
4276
const char* ImGui::GetClipboardText()
4277
0
{
4278
0
    ImGuiContext& g = *GImGui;
4279
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4280
0
}
4281
4282
void ImGui::SetClipboardText(const char* text)
4283
0
{
4284
0
    ImGuiContext& g = *GImGui;
4285
0
    if (g.IO.SetClipboardTextFn)
4286
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4287
0
}
4288
4289
const char* ImGui::GetVersion()
4290
0
{
4291
0
    return IMGUI_VERSION;
4292
0
}
4293
4294
ImGuiIO& ImGui::GetIO()
4295
67.4k
{
4296
67.4k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4297
67.4k
    return GImGui->IO;
4298
67.4k
}
4299
4300
ImGuiPlatformIO& ImGui::GetPlatformIO()
4301
0
{
4302
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4303
0
    return GImGui->PlatformIO;
4304
0
}
4305
4306
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4307
ImDrawData* ImGui::GetDrawData()
4308
18.0k
{
4309
18.0k
    ImGuiContext& g = *GImGui;
4310
18.0k
    ImGuiViewportP* viewport = g.Viewports[0];
4311
18.0k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4312
18.0k
}
4313
4314
double ImGui::GetTime()
4315
1
{
4316
1
    return GImGui->Time;
4317
1
}
4318
4319
int ImGui::GetFrameCount()
4320
0
{
4321
0
    return GImGui->FrameCount;
4322
0
}
4323
4324
static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4325
0
{
4326
    // Create the draw list on demand, because they are not frequently used for all viewports
4327
0
    ImGuiContext& g = *GImGui;
4328
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
4329
0
    ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
4330
0
    if (draw_list == NULL)
4331
0
    {
4332
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4333
0
        draw_list->_OwnerName = drawlist_name;
4334
0
        viewport->DrawLists[drawlist_no] = draw_list;
4335
0
    }
4336
4337
    // Our ImDrawList system requires that there is always a command
4338
0
    if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
4339
0
    {
4340
0
        draw_list->_ResetForNewFrame();
4341
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4342
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4343
0
        viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
4344
0
    }
4345
0
    return draw_list;
4346
0
}
4347
4348
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4349
0
{
4350
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4351
0
}
4352
4353
ImDrawList* ImGui::GetBackgroundDrawList()
4354
0
{
4355
0
    ImGuiContext& g = *GImGui;
4356
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4357
0
}
4358
4359
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4360
0
{
4361
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4362
0
}
4363
4364
ImDrawList* ImGui::GetForegroundDrawList()
4365
0
{
4366
0
    ImGuiContext& g = *GImGui;
4367
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4368
0
}
4369
4370
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4371
0
{
4372
0
    return &GImGui->DrawListSharedData;
4373
0
}
4374
4375
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4376
12
{
4377
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4378
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4379
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4380
12
    ImGuiContext& g = *GImGui;
4381
12
    FocusWindow(window);
4382
12
    SetActiveID(window->MoveId, window);
4383
12
    g.NavDisableHighlight = true;
4384
12
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4385
12
    g.ActiveIdNoClearOnFocusLoss = true;
4386
12
    SetActiveIdUsingAllKeyboardKeys();
4387
4388
12
    bool can_move_window = true;
4389
12
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4390
0
        can_move_window = false;
4391
12
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4392
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4393
0
            can_move_window = false;
4394
12
    if (can_move_window)
4395
12
        g.MovingWindow = window;
4396
12
}
4397
4398
// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4399
// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
4400
// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
4401
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
4402
3
{
4403
3
    ImGuiContext& g = *GImGui;
4404
3
    bool can_undock_node = false;
4405
3
    if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
4406
0
    {
4407
        // Can undock if:
4408
        // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
4409
        // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
4410
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4411
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4412
0
            if (undock_floating_node || root_node->IsDockSpace())
4413
0
                can_undock_node = true;
4414
0
    }
4415
4416
3
    const bool clicked = IsMouseClicked(0);
4417
3
    const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
4418
3
    if (can_undock_node && dragging)
4419
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4420
3
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4421
3
        StartMouseMovingWindow(window);
4422
3
}
4423
4424
// Handle mouse moving window
4425
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4426
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4427
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4428
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4429
void ImGui::UpdateMouseMovingWindowNewFrame()
4430
18.0k
{
4431
18.0k
    ImGuiContext& g = *GImGui;
4432
18.0k
    if (g.MovingWindow != NULL)
4433
37
    {
4434
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4435
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4436
37
        KeepAliveID(g.ActiveId);
4437
37
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4438
37
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4439
4440
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4441
37
        const bool window_disappared = (!moving_window->WasActive && !moving_window->Active);
4442
37
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4443
25
        {
4444
25
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4445
25
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4446
2
            {
4447
2
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4448
2
                if (moving_window->Viewport && moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4449
0
                {
4450
0
                    moving_window->Viewport->Pos = pos;
4451
0
                    moving_window->Viewport->UpdateWorkRect();
4452
0
                }
4453
2
            }
4454
25
            FocusWindow(g.MovingWindow);
4455
25
        }
4456
12
        else
4457
12
        {
4458
12
            if (!window_disappared)
4459
12
            {
4460
                // Try to merge the window back into the main viewport.
4461
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4462
12
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4463
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4464
4465
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4466
12
                if (moving_window->Viewport && !IsDragDropPayloadBeingAccepted())
4467
12
                    g.MouseViewport = moving_window->Viewport;
4468
4469
                // Clear the NoInput window flag set by the Viewport system
4470
12
                if (moving_window->Viewport)
4471
12
                    moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
4472
12
            }
4473
4474
12
            g.MovingWindow = NULL;
4475
12
            ClearActiveID();
4476
12
        }
4477
37
    }
4478
17.9k
    else
4479
17.9k
    {
4480
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4481
17.9k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4482
0
        {
4483
0
            KeepAliveID(g.ActiveId);
4484
0
            if (!g.IO.MouseDown[0])
4485
0
                ClearActiveID();
4486
0
        }
4487
17.9k
    }
4488
18.0k
}
4489
4490
// Initiate moving window when clicking on empty space or title bar.
4491
// Handle left-click and right-click focus.
4492
void ImGui::UpdateMouseMovingWindowEndFrame()
4493
18.0k
{
4494
18.0k
    ImGuiContext& g = *GImGui;
4495
18.0k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4496
328
        return;
4497
4498
    // Unless we just made a window/popup appear
4499
17.6k
    if (g.NavWindow && g.NavWindow->Appearing)
4500
2
        return;
4501
4502
    // Click on empty space to focus window and start moving
4503
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4504
17.6k
    if (g.IO.MouseClicked[0])
4505
332
    {
4506
        // Handle the edge case of a popup being closed while clicking in its empty space.
4507
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4508
332
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4509
332
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4510
4511
332
        if (root_window != NULL && !is_closed_popup)
4512
9
        {
4513
9
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4514
4515
            // Cancel moving if clicked outside of title bar
4516
9
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4517
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4518
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4519
0
                        g.MovingWindow = NULL;
4520
4521
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4522
9
            if (g.HoveredIdDisabled)
4523
0
                g.MovingWindow = NULL;
4524
9
        }
4525
323
        else if (root_window == NULL && g.NavWindow != NULL)
4526
24
        {
4527
            // Clicking on void disable focus
4528
24
            FocusWindow(NULL, ImGuiFocusRequestFlags_UnlessBelowModal);
4529
24
        }
4530
332
    }
4531
4532
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4533
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4534
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4535
17.6k
    if (g.IO.MouseClicked[1])
4536
78
    {
4537
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4538
        // This is where we can trim the popup stack.
4539
78
        ImGuiWindow* modal = GetTopMostPopupModal();
4540
78
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4541
78
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4542
78
    }
4543
17.6k
}
4544
4545
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4546
// Need to keep in sync with SetWindowPos()
4547
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4548
0
{
4549
0
    window->Pos += delta;
4550
0
    window->ClipRect.Translate(delta);
4551
0
    window->OuterRectClipped.Translate(delta);
4552
0
    window->InnerRect.Translate(delta);
4553
0
    window->DC.CursorPos += delta;
4554
0
    window->DC.CursorStartPos += delta;
4555
0
    window->DC.CursorMaxPos += delta;
4556
0
    window->DC.IdealMaxPos += delta;
4557
0
}
4558
4559
static void ScaleWindow(ImGuiWindow* window, float scale)
4560
0
{
4561
0
    ImVec2 origin = window->Viewport->Pos;
4562
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4563
0
    window->Size = ImFloor(window->Size * scale);
4564
0
    window->SizeFull = ImFloor(window->SizeFull * scale);
4565
0
    window->ContentSize = ImFloor(window->ContentSize * scale);
4566
0
}
4567
4568
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4569
63.5k
{
4570
63.5k
    return (window->Active) && (!window->Hidden);
4571
63.5k
}
4572
4573
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4574
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4575
18.0k
{
4576
18.0k
    ImGuiContext& g = *GImGui;
4577
18.0k
    ImGuiIO& io = g.IO;
4578
18.0k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4579
4580
    // Find the window hovered by mouse:
4581
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4582
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4583
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4584
18.0k
    bool clear_hovered_windows = false;
4585
18.0k
    FindHoveredWindow();
4586
18.0k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4587
4588
    // Modal windows prevents mouse from hovering behind them.
4589
18.0k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4590
18.0k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4591
0
        clear_hovered_windows = true;
4592
4593
    // Disabled mouse?
4594
18.0k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4595
0
        clear_hovered_windows = true;
4596
4597
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4598
    // won't report hovering nor request capture even while dragging over our windows afterward.
4599
18.0k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4600
18.0k
    const bool has_open_modal = (modal_window != NULL);
4601
18.0k
    int mouse_earliest_down = -1;
4602
18.0k
    bool mouse_any_down = false;
4603
108k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4604
90.0k
    {
4605
90.0k
        if (io.MouseClicked[i])
4606
789
        {
4607
789
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4608
789
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4609
789
        }
4610
90.0k
        mouse_any_down |= io.MouseDown[i];
4611
90.0k
        if (io.MouseDown[i])
4612
5.06k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4613
3.60k
                mouse_earliest_down = i;
4614
90.0k
    }
4615
18.0k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4616
18.0k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4617
4618
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4619
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4620
18.0k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4621
18.0k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4622
2.52k
        clear_hovered_windows = true;
4623
4624
18.0k
    if (clear_hovered_windows)
4625
2.52k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4626
4627
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4628
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4629
18.0k
    if (g.WantCaptureMouseNextFrame != -1)
4630
0
    {
4631
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4632
0
    }
4633
18.0k
    else
4634
18.0k
    {
4635
18.0k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4636
18.0k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4637
18.0k
    }
4638
4639
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4640
18.0k
    if (g.WantCaptureKeyboardNextFrame != -1)
4641
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4642
18.0k
    else
4643
18.0k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4644
18.0k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4645
5.29k
        io.WantCaptureKeyboard = true;
4646
4647
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4648
18.0k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4649
18.0k
}
4650
4651
void ImGui::NewFrame()
4652
18.0k
{
4653
18.0k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4654
18.0k
    ImGuiContext& g = *GImGui;
4655
4656
    // Remove pending delete hooks before frame start.
4657
    // This deferred removal avoid issues of removal while iterating the hook vector
4658
18.0k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4659
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4660
0
            g.Hooks.erase(&g.Hooks[n]);
4661
4662
18.0k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4663
4664
    // Check and assert for various common IO and Configuration mistakes
4665
18.0k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4666
18.0k
    ErrorCheckNewFrameSanityChecks();
4667
18.0k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4668
4669
    // Load settings on first frame, save settings when modified (after a delay)
4670
18.0k
    UpdateSettings();
4671
4672
18.0k
    g.Time += g.IO.DeltaTime;
4673
18.0k
    g.WithinFrameScope = true;
4674
18.0k
    g.FrameCount += 1;
4675
18.0k
    g.TooltipOverrideCount = 0;
4676
18.0k
    g.WindowsActiveCount = 0;
4677
18.0k
    g.MenusIdSubmittedThisFrame.resize(0);
4678
4679
    // Calculate frame-rate for the user, as a purely luxurious feature
4680
18.0k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4681
18.0k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4682
18.0k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4683
18.0k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4684
18.0k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4685
4686
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4687
18.0k
    g.InputEventsTrail.resize(0);
4688
18.0k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4689
4690
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4691
18.0k
    UpdateViewportsNewFrame();
4692
4693
    // Setup current font and draw list shared data
4694
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4695
18.0k
    g.IO.Fonts->Locked = true;
4696
18.0k
    SetCurrentFont(GetDefaultFont());
4697
18.0k
    IM_ASSERT(g.Font->IsLoaded());
4698
18.0k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4699
36.0k
    for (int n = 0; n < g.Viewports.Size; n++)
4700
18.0k
        virtual_space.Add(g.Viewports[n]->GetMainRect());
4701
18.0k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4702
18.0k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4703
18.0k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4704
18.0k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4705
18.0k
    if (g.Style.AntiAliasedLines)
4706
18.0k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4707
18.0k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4708
18.0k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4709
18.0k
    if (g.Style.AntiAliasedFill)
4710
18.0k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4711
18.0k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4712
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4713
4714
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4715
36.0k
    for (int n = 0; n < g.Viewports.Size; n++)
4716
18.0k
    {
4717
18.0k
        ImGuiViewportP* viewport = g.Viewports[n];
4718
18.0k
        viewport->DrawData = NULL;
4719
18.0k
        viewport->DrawDataP.Clear();
4720
18.0k
    }
4721
4722
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4723
18.0k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4724
5
        KeepAliveID(g.DragDropPayload.SourceId);
4725
4726
    // Update HoveredId data
4727
18.0k
    if (!g.HoveredIdPreviousFrame)
4728
17.7k
        g.HoveredIdTimer = 0.0f;
4729
18.0k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4730
17.8k
        g.HoveredIdNotActiveTimer = 0.0f;
4731
18.0k
    if (g.HoveredId)
4732
287
        g.HoveredIdTimer += g.IO.DeltaTime;
4733
18.0k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4734
193
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4735
18.0k
    g.HoveredIdPreviousFrame = g.HoveredId;
4736
18.0k
    g.HoveredId = 0;
4737
18.0k
    g.HoveredIdAllowOverlap = false;
4738
18.0k
    g.HoveredIdDisabled = false;
4739
4740
    // Clear ActiveID if the item is not alive anymore.
4741
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4742
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4743
18.0k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4744
0
    {
4745
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4746
0
        ClearActiveID();
4747
0
    }
4748
4749
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4750
18.0k
    if (g.ActiveId)
4751
143
        g.ActiveIdTimer += g.IO.DeltaTime;
4752
18.0k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4753
18.0k
    g.ActiveIdPreviousFrame = g.ActiveId;
4754
18.0k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4755
18.0k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4756
18.0k
    g.ActiveIdIsAlive = 0;
4757
18.0k
    g.ActiveIdHasBeenEditedThisFrame = false;
4758
18.0k
    g.ActiveIdPreviousFrameIsAlive = false;
4759
18.0k
    g.ActiveIdIsJustActivated = false;
4760
18.0k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4761
0
        g.TempInputId = 0;
4762
18.0k
    if (g.ActiveId == 0)
4763
17.8k
    {
4764
17.8k
        g.ActiveIdUsingNavDirMask = 0x00;
4765
17.8k
        g.ActiveIdUsingAllKeyboardKeys = false;
4766
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4767
        g.ActiveIdUsingNavInputMask = 0x00;
4768
#endif
4769
17.8k
    }
4770
4771
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4772
    if (g.ActiveId == 0)
4773
        g.ActiveIdUsingNavInputMask = 0;
4774
    else if (g.ActiveIdUsingNavInputMask != 0)
4775
    {
4776
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4777
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4778
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4779
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4780
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4781
            IM_ASSERT(0); // Other values unsupported
4782
    }
4783
#endif
4784
4785
    // Record when we have been stationary as this state is preserved while over same item.
4786
    // FIXME: The way this is expressed means user cannot alter HoverStationaryDelay during the frame to use varying values.
4787
    // To allow this we should store HoverItemMaxStationaryTime+ID and perform the >= check in IsItemHovered() function.
4788
18.0k
    if (g.HoverItemDelayId != 0 && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4789
0
        g.HoverItemUnlockedStationaryId = g.HoverItemDelayId;
4790
18.0k
    else if (g.HoverItemDelayId == 0)
4791
18.0k
        g.HoverItemUnlockedStationaryId = 0;
4792
18.0k
    if (g.HoveredWindow != NULL && g.MouseStationaryTimer >= g.Style.HoverStationaryDelay)
4793
333
        g.HoverWindowUnlockedStationaryId = g.HoveredWindow->ID;
4794
17.6k
    else if (g.HoveredWindow == NULL)
4795
17.6k
        g.HoverWindowUnlockedStationaryId = 0;
4796
4797
    // Update hover delay for IsItemHovered() with delays and tooltips
4798
18.0k
    g.HoverItemDelayIdPreviousFrame = g.HoverItemDelayId;
4799
18.0k
    if (g.HoverItemDelayId != 0)
4800
0
    {
4801
0
        g.HoverItemDelayTimer += g.IO.DeltaTime;
4802
0
        g.HoverItemDelayClearTimer = 0.0f;
4803
0
        g.HoverItemDelayId = 0;
4804
0
    }
4805
18.0k
    else if (g.HoverItemDelayTimer > 0.0f)
4806
0
    {
4807
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4808
        // We could expose 0.25f as style.HoverClearDelay but I am not sure of the logic yet, this is particularly subtle.
4809
0
        g.HoverItemDelayClearTimer += g.IO.DeltaTime;
4810
0
        if (g.HoverItemDelayClearTimer >= ImMax(0.25f, g.IO.DeltaTime * 2.0f)) // ~7 frames at 30 Hz + allow for low framerate
4811
0
            g.HoverItemDelayTimer = g.HoverItemDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4812
0
    }
4813
4814
    // Drag and drop
4815
18.0k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4816
18.0k
    g.DragDropAcceptIdCurr = 0;
4817
18.0k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4818
18.0k
    g.DragDropWithinSource = false;
4819
18.0k
    g.DragDropWithinTarget = false;
4820
18.0k
    g.DragDropHoldJustPressedId = 0;
4821
4822
    // Close popups on focus lost (currently wip/opt-in)
4823
    //if (g.IO.AppFocusLost)
4824
    //    ClosePopupsExceptModals();
4825
4826
    // Update keyboard input state
4827
18.0k
    UpdateKeyboardInputs();
4828
4829
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4830
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4831
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4832
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4833
4834
    // Update gamepad/keyboard navigation
4835
18.0k
    NavUpdate();
4836
4837
    // Update mouse input state
4838
18.0k
    UpdateMouseInputs();
4839
4840
    // Undocking
4841
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4842
18.0k
    DockContextNewFrameUpdateUndocking(&g);
4843
4844
    // Find hovered window
4845
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4846
18.0k
    UpdateHoveredWindowAndCaptureFlags();
4847
4848
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4849
18.0k
    UpdateMouseMovingWindowNewFrame();
4850
4851
    // Background darkening/whitening
4852
18.0k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4853
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4854
18.0k
    else
4855
18.0k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4856
4857
18.0k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4858
18.0k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4859
4860
    // Platform IME data: reset for the frame
4861
18.0k
    g.PlatformImeDataPrev = g.PlatformImeData;
4862
18.0k
    g.PlatformImeData.WantVisible = false;
4863
4864
    // Mouse wheel scrolling, scale
4865
18.0k
    UpdateMouseWheel();
4866
4867
    // Mark all windows as not visible and compact unused memory.
4868
18.0k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4869
18.0k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4870
72.0k
    for (int i = 0; i != g.Windows.Size; i++)
4871
54.0k
    {
4872
54.0k
        ImGuiWindow* window = g.Windows[i];
4873
54.0k
        window->WasActive = window->Active;
4874
54.0k
        window->Active = false;
4875
54.0k
        window->WriteAccessed = false;
4876
54.0k
        window->BeginCountPreviousFrame = window->BeginCount;
4877
54.0k
        window->BeginCount = 0;
4878
4879
        // Garbage collect transient buffers of recently unused windows
4880
54.0k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4881
1
            GcCompactTransientWindowBuffers(window);
4882
54.0k
    }
4883
4884
    // Garbage collect transient buffers of recently unused tables
4885
18.0k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4886
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4887
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4888
18.0k
    for (int i = 0; i < g.TablesTempData.Size; i++)
4889
0
        if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
4890
0
            TableGcCompactTransientBuffers(&g.TablesTempData[i]);
4891
18.0k
    if (g.GcCompactAll)
4892
0
        GcCompactTransientMiscBuffers();
4893
18.0k
    g.GcCompactAll = false;
4894
4895
    // Closing the focused window restore focus to the first active root window in descending z-order
4896
18.0k
    if (g.NavWindow && !g.NavWindow->WasActive)
4897
1
        FocusTopMostWindowUnderOne(NULL, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild);
4898
4899
    // No window should be open at the beginning of the frame.
4900
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4901
18.0k
    g.CurrentWindowStack.resize(0);
4902
18.0k
    g.BeginPopupStack.resize(0);
4903
18.0k
    g.ItemFlagsStack.resize(0);
4904
18.0k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4905
18.0k
    g.GroupStack.resize(0);
4906
4907
    // Docking
4908
18.0k
    DockContextNewFrameUpdateDocking(&g);
4909
4910
    // [DEBUG] Update debug features
4911
18.0k
    UpdateDebugToolItemPicker();
4912
18.0k
    UpdateDebugToolStackQueries();
4913
18.0k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4914
0
        g.DebugLocateId = 0;
4915
18.0k
    if (g.DebugLogClipperAutoDisableFrames > 0 && --g.DebugLogClipperAutoDisableFrames == 0)
4916
0
    {
4917
0
        DebugLog("(Auto-disabled ImGuiDebugLogFlags_EventClipper to avoid spamming)\n");
4918
0
        g.DebugLogFlags &= ~ImGuiDebugLogFlags_EventClipper;
4919
0
    }
4920
4921
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4922
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4923
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4924
18.0k
    g.WithinFrameScopeWithImplicitWindow = true;
4925
18.0k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4926
18.0k
    Begin("Debug##Default");
4927
18.0k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4928
4929
    // [DEBUG] When io.ConfigDebugBeginReturnValue is set, we make Begin()/BeginChild() return false at different level of the window-stack,
4930
    // allowing to validate correct Begin/End behavior in user code.
4931
18.0k
    if (g.IO.ConfigDebugBeginReturnValueLoop)
4932
0
        g.DebugBeginReturnValueCullDepth = (g.DebugBeginReturnValueCullDepth == -1) ? 0 : ((g.DebugBeginReturnValueCullDepth + ((g.FrameCount % 4) == 0 ? 1 : 0)) % 10);
4933
18.0k
    else
4934
18.0k
        g.DebugBeginReturnValueCullDepth = -1;
4935
4936
18.0k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
4937
18.0k
}
4938
4939
// FIXME: Add a more explicit sort order in the window structure.
4940
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
4941
0
{
4942
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
4943
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
4944
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
4945
0
        return d;
4946
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
4947
0
        return d;
4948
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
4949
0
}
4950
4951
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
4952
54.0k
{
4953
54.0k
    out_sorted_windows->push_back(window);
4954
54.0k
    if (window->Active)
4955
27.5k
    {
4956
27.5k
        int count = window->DC.ChildWindows.Size;
4957
27.5k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
4958
37.0k
        for (int i = 0; i < count; i++)
4959
9.51k
        {
4960
9.51k
            ImGuiWindow* child = window->DC.ChildWindows[i];
4961
9.51k
            if (child->Active)
4962
9.51k
                AddWindowToSortBuffer(out_sorted_windows, child);
4963
9.51k
        }
4964
27.5k
    }
4965
54.0k
}
4966
4967
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
4968
26.5k
{
4969
26.5k
    if (draw_list->CmdBuffer.Size == 0)
4970
0
        return;
4971
26.5k
    if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
4972
28
        return;
4973
4974
    // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
4975
    // May trigger for you if you are using PrimXXX functions incorrectly.
4976
26.5k
    IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
4977
26.5k
    IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
4978
26.5k
    if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
4979
26.5k
        IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
4980
4981
    // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
4982
    // If this assert triggers because you are drawing lots of stuff manually:
4983
    // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
4984
    //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
4985
    // - If you want large meshes with more than 64K vertices, you can either:
4986
    //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
4987
    //       Most example backends already support this from 1.71. Pre-1.71 backends won't.
4988
    //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
4989
    //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
4990
    //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
4991
    //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
4992
    //       Your own engine or render API may use different parameters or function calls to specify index sizes.
4993
    //       2 and 4 bytes indices are generally supported by most graphics API.
4994
    // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
4995
    //   the 64K limit to split your draw commands in multiple draw lists.
4996
26.5k
    if (sizeof(ImDrawIdx) == 2)
4997
26.5k
        IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
4998
4999
26.5k
    out_list->push_back(draw_list);
5000
26.5k
}
5001
5002
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
5003
26.5k
{
5004
26.5k
    ImGuiContext& g = *GImGui;
5005
26.5k
    ImGuiViewportP* viewport = window->Viewport;
5006
26.5k
    IM_ASSERT(viewport != NULL);
5007
26.5k
    g.IO.MetricsRenderWindows++;
5008
26.5k
    if (window->Flags & ImGuiWindowFlags_DockNodeHost)
5009
0
        window->DrawList->ChannelsMerge();
5010
26.5k
    AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
5011
36.0k
    for (int i = 0; i < window->DC.ChildWindows.Size; i++)
5012
9.51k
    {
5013
9.51k
        ImGuiWindow* child = window->DC.ChildWindows[i];
5014
9.51k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
5015
8.56k
            AddWindowToDrawData(child, layer);
5016
9.51k
    }
5017
26.5k
}
5018
5019
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
5020
18.0k
{
5021
18.0k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
5022
18.0k
}
5023
5024
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
5025
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
5026
18.0k
{
5027
18.0k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
5028
18.0k
}
5029
5030
void ImDrawDataBuilder::FlattenIntoSingleLayer()
5031
18.0k
{
5032
18.0k
    int n = Layers[0].Size;
5033
18.0k
    int size = n;
5034
36.0k
    for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
5035
18.0k
        size += Layers[i].Size;
5036
18.0k
    Layers[0].resize(size);
5037
36.0k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
5038
18.0k
    {
5039
18.0k
        ImVector<ImDrawList*>& layer = Layers[layer_n];
5040
18.0k
        if (layer.empty())
5041
18.0k
            continue;
5042
0
        memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
5043
0
        n += layer.Size;
5044
0
        layer.resize(0);
5045
0
    }
5046
18.0k
}
5047
5048
static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
5049
18.0k
{
5050
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
5051
    // and to allow applications/backends to easily skip rendering.
5052
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
5053
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
5054
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
5055
18.0k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0;
5056
5057
18.0k
    ImGuiIO& io = ImGui::GetIO();
5058
18.0k
    ImDrawData* draw_data = &viewport->DrawDataP;
5059
18.0k
    viewport->DrawData = draw_data; // Make publicly accessible
5060
18.0k
    draw_data->Valid = true;
5061
18.0k
    draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
5062
18.0k
    draw_data->CmdListsCount = draw_lists->Size;
5063
18.0k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
5064
18.0k
    draw_data->DisplayPos = viewport->Pos;
5065
18.0k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
5066
18.0k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
5067
18.0k
    draw_data->OwnerViewport = viewport;
5068
44.5k
    for (int n = 0; n < draw_lists->Size; n++)
5069
26.5k
    {
5070
26.5k
        ImDrawList* draw_list = draw_lists->Data[n];
5071
26.5k
        draw_list->_PopUnusedDrawCmd();
5072
26.5k
        draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
5073
26.5k
        draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
5074
26.5k
    }
5075
18.0k
}
5076
5077
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
5078
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
5079
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
5080
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
5081
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
5082
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
5083
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
5084
91.0k
{
5085
91.0k
    ImGuiWindow* window = GetCurrentWindow();
5086
91.0k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
5087
91.0k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5088
91.0k
}
5089
5090
void ImGui::PopClipRect()
5091
45.5k
{
5092
45.5k
    ImGuiWindow* window = GetCurrentWindow();
5093
45.5k
    window->DrawList->PopClipRect();
5094
45.5k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
5095
45.5k
}
5096
5097
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
5098
0
{
5099
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
5100
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
5101
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
5102
0
    return window;
5103
0
}
5104
5105
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
5106
0
{
5107
0
    if ((col & IM_COL32_A_MASK) == 0)
5108
0
        return;
5109
5110
0
    ImGuiViewportP* viewport = window->Viewport;
5111
0
    ImRect viewport_rect = viewport->GetMainRect();
5112
5113
    // Draw behind window by moving the draw command at the FRONT of the draw list
5114
0
    {
5115
        // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
5116
        // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
5117
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
5118
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
5119
0
        if (draw_list->CmdBuffer.Size == 0)
5120
0
            draw_list->AddDrawCmd();
5121
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
5122
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
5123
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
5124
0
        IM_ASSERT(cmd.ElemCount == 6);
5125
0
        draw_list->CmdBuffer.pop_back();
5126
0
        draw_list->CmdBuffer.push_front(cmd);
5127
0
        draw_list->PopClipRect();
5128
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
5129
0
    }
5130
5131
    // Draw over sibling docking nodes in a same docking tree
5132
0
    if (window->RootWindow->DockIsActive)
5133
0
    {
5134
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
5135
0
        if (draw_list->CmdBuffer.Size == 0)
5136
0
            draw_list->AddDrawCmd();
5137
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
5138
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
5139
0
        draw_list->PopClipRect();
5140
0
    }
5141
0
}
5142
5143
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
5144
0
{
5145
0
    ImGuiContext& g = *GImGui;
5146
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
5147
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
5148
0
    {
5149
0
        ImGuiWindow* window = g.Windows[i];
5150
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
5151
0
            continue;
5152
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
5153
0
            break;
5154
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
5155
0
            bottom_most_visible_window = window;
5156
0
    }
5157
0
    return bottom_most_visible_window;
5158
0
}
5159
5160
static void ImGui::RenderDimmedBackgrounds()
5161
18.0k
{
5162
18.0k
    ImGuiContext& g = *GImGui;
5163
18.0k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
5164
18.0k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5165
18.0k
        return;
5166
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5167
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5168
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5169
0
        return;
5170
5171
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5172
0
    if (dim_bg_for_modal)
5173
0
    {
5174
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5175
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5176
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5177
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5178
0
    }
5179
0
    else if (dim_bg_for_window_list)
5180
0
    {
5181
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5182
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5183
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5184
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5185
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5186
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5187
5188
        // Draw border around CTRL+Tab target window
5189
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5190
0
        ImGuiViewport* viewport = window->Viewport;
5191
0
        float distance = g.FontSize;
5192
0
        ImRect bb = window->Rect();
5193
0
        bb.Expand(distance);
5194
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5195
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5196
0
        if (window->DrawList->CmdBuffer.Size == 0)
5197
0
            window->DrawList->AddDrawCmd();
5198
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5199
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5200
0
        window->DrawList->PopClipRect();
5201
0
    }
5202
5203
    // Draw dimming background on _other_ viewports than the ones our windows are in
5204
0
    for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
5205
0
    {
5206
0
        ImGuiViewportP* viewport = g.Viewports[viewport_n];
5207
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5208
0
            continue;
5209
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5210
0
            continue;
5211
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5212
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5213
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5214
0
    }
5215
0
}
5216
5217
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5218
void ImGui::EndFrame()
5219
36.0k
{
5220
36.0k
    ImGuiContext& g = *GImGui;
5221
36.0k
    IM_ASSERT(g.Initialized);
5222
5223
    // Don't process EndFrame() multiple times.
5224
36.0k
    if (g.FrameCountEnded == g.FrameCount)
5225
18.0k
        return;
5226
18.0k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5227
5228
18.0k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5229
5230
18.0k
    ErrorCheckEndFrameSanityChecks();
5231
5232
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5233
18.0k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5234
18.0k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5235
0
    {
5236
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5237
0
        IMGUI_DEBUG_LOG_IO("[io] Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5238
0
        if (viewport == NULL)
5239
0
            viewport = GetMainViewport();
5240
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5241
        if (viewport->PlatformHandleRaw == NULL && g.IO.ImeWindowHandle != NULL)
5242
        {
5243
            viewport->PlatformHandleRaw = g.IO.ImeWindowHandle;
5244
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5245
            viewport->PlatformHandleRaw = NULL;
5246
        }
5247
        else
5248
#endif
5249
0
        {
5250
0
            g.IO.SetPlatformImeDataFn(viewport, ime_data);
5251
0
        }
5252
0
    }
5253
5254
    // Hide implicit/fallback "Debug" window if it hasn't been used
5255
18.0k
    g.WithinFrameScopeWithImplicitWindow = false;
5256
18.0k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5257
18.0k
        g.CurrentWindow->Active = false;
5258
18.0k
    End();
5259
5260
    // Update navigation: CTRL+Tab, wrap-around requests
5261
18.0k
    NavEndFrame();
5262
5263
    // Update docking
5264
18.0k
    DockContextEndFrame(&g);
5265
5266
18.0k
    SetCurrentViewport(NULL, NULL);
5267
5268
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5269
18.0k
    if (g.DragDropActive)
5270
11
    {
5271
11
        bool is_delivered = g.DragDropPayload.Delivery;
5272
11
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5273
11
        if (is_delivered || is_elapsed)
5274
3
            ClearDragDrop();
5275
11
    }
5276
5277
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5278
18.0k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5279
0
    {
5280
0
        g.DragDropWithinSource = true;
5281
0
        SetTooltip("...");
5282
0
        g.DragDropWithinSource = false;
5283
0
    }
5284
5285
    // End frame
5286
18.0k
    g.WithinFrameScope = false;
5287
18.0k
    g.FrameCountEnded = g.FrameCount;
5288
5289
    // Initiate moving window + handle left-click and right-click focus
5290
18.0k
    UpdateMouseMovingWindowEndFrame();
5291
5292
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5293
18.0k
    UpdateViewportsEndFrame();
5294
5295
    // Sort the window list so that all child windows are after their parent
5296
    // We cannot do that on FocusWindow() because children may not exist yet
5297
18.0k
    g.WindowsTempSortBuffer.resize(0);
5298
18.0k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5299
72.0k
    for (int i = 0; i != g.Windows.Size; i++)
5300
54.0k
    {
5301
54.0k
        ImGuiWindow* window = g.Windows[i];
5302
54.0k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5303
9.51k
            continue;
5304
44.5k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5305
44.5k
    }
5306
5307
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5308
18.0k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5309
18.0k
    g.Windows.swap(g.WindowsTempSortBuffer);
5310
18.0k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5311
5312
    // Unlock font atlas
5313
18.0k
    g.IO.Fonts->Locked = false;
5314
5315
    // Clear Input data for next frame
5316
18.0k
    g.IO.AppFocusLost = false;
5317
18.0k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5318
18.0k
    g.IO.InputQueueCharacters.resize(0);
5319
5320
18.0k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5321
18.0k
}
5322
5323
// Prepare the data for rendering so you can call GetDrawData()
5324
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5325
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5326
void ImGui::Render()
5327
18.0k
{
5328
18.0k
    ImGuiContext& g = *GImGui;
5329
18.0k
    IM_ASSERT(g.Initialized);
5330
5331
18.0k
    if (g.FrameCountEnded != g.FrameCount)
5332
18.0k
        EndFrame();
5333
18.0k
    const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
5334
18.0k
    g.FrameCountRendered = g.FrameCount;
5335
18.0k
    g.IO.MetricsRenderWindows = 0;
5336
5337
18.0k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5338
5339
    // Add background ImDrawList (for each active viewport)
5340
36.0k
    for (int n = 0; n != g.Viewports.Size; n++)
5341
18.0k
    {
5342
18.0k
        ImGuiViewportP* viewport = g.Viewports[n];
5343
18.0k
        viewport->DrawDataBuilder.Clear();
5344
18.0k
        if (viewport->DrawLists[0] != NULL)
5345
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5346
18.0k
    }
5347
5348
    // Add ImDrawList to render
5349
18.0k
    ImGuiWindow* windows_to_render_top_most[2];
5350
18.0k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5351
18.0k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5352
72.0k
    for (int n = 0; n != g.Windows.Size; n++)
5353
54.0k
    {
5354
54.0k
        ImGuiWindow* window = g.Windows[n];
5355
54.0k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5356
54.0k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5357
18.0k
            AddRootWindowToDrawData(window);
5358
54.0k
    }
5359
54.0k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5360
36.0k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5361
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5362
5363
    // Draw modal/window whitening backgrounds
5364
18.0k
    if (first_render_of_frame)
5365
18.0k
        RenderDimmedBackgrounds();
5366
5367
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5368
18.0k
    if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None)
5369
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5370
5371
    // Setup ImDrawData structures for end-user
5372
18.0k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5373
36.0k
    for (int n = 0; n < g.Viewports.Size; n++)
5374
18.0k
    {
5375
18.0k
        ImGuiViewportP* viewport = g.Viewports[n];
5376
18.0k
        viewport->DrawDataBuilder.FlattenIntoSingleLayer();
5377
5378
        // Add foreground ImDrawList (for each active viewport)
5379
18.0k
        if (viewport->DrawLists[1] != NULL)
5380
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5381
5382
18.0k
        SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
5383
18.0k
        ImDrawData* draw_data = viewport->DrawData;
5384
18.0k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5385
18.0k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5386
18.0k
    }
5387
5388
18.0k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5389
18.0k
}
5390
5391
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5392
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5393
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5394
36.0k
{
5395
36.0k
    ImGuiContext& g = *GImGui;
5396
5397
36.0k
    const char* text_display_end;
5398
36.0k
    if (hide_text_after_double_hash)
5399
36.0k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5400
0
    else
5401
0
        text_display_end = text_end;
5402
5403
36.0k
    ImFont* font = g.Font;
5404
36.0k
    const float font_size = g.FontSize;
5405
36.0k
    if (text == text_display_end)
5406
0
        return ImVec2(0.0f, font_size);
5407
36.0k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5408
5409
    // Round
5410
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5411
    // FIXME: Investigate using ceilf or e.g.
5412
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5413
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5414
36.0k
    text_size.x = IM_FLOOR(text_size.x + 0.99999f);
5415
5416
36.0k
    return text_size;
5417
36.0k
}
5418
5419
// Find window given position, search front-to-back
5420
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5421
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5422
// called, aka before the next Begin(). Moving window isn't affected.
5423
static void FindHoveredWindow()
5424
18.0k
{
5425
18.0k
    ImGuiContext& g = *GImGui;
5426
5427
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5428
18.0k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5429
18.0k
    if (g.MovingWindow)
5430
37
        g.MovingWindow->Viewport = g.MouseViewport;
5431
5432
18.0k
    ImGuiWindow* hovered_window = NULL;
5433
18.0k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5434
18.0k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5435
37
        hovered_window = g.MovingWindow;
5436
5437
18.0k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5438
18.0k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5439
71.3k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5440
53.6k
    {
5441
53.6k
        ImGuiWindow* window = g.Windows[i];
5442
53.6k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5443
53.6k
        if (!window->Active || window->Hidden)
5444
27.1k
            continue;
5445
26.5k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5446
0
            continue;
5447
26.5k
        IM_ASSERT(window->Viewport);
5448
26.5k
        if (window->Viewport != g.MouseViewport)
5449
0
            continue;
5450
5451
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5452
26.5k
        ImRect bb(window->OuterRectClipped);
5453
26.5k
        if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
5454
8.56k
            bb.Expand(padding_regular);
5455
18.0k
        else
5456
18.0k
            bb.Expand(padding_for_resize);
5457
26.5k
        if (!bb.Contains(g.IO.MousePos))
5458
26.1k
            continue;
5459
5460
        // Support for one rectangular hole in any given window
5461
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5462
376
        if (window->HitTestHoleSize.x != 0)
5463
0
        {
5464
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5465
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5466
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5467
0
                continue;
5468
0
        }
5469
5470
376
        if (hovered_window == NULL)
5471
352
            hovered_window = window;
5472
376
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5473
376
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5474
352
            hovered_window_ignoring_moving_window = window;
5475
376
        if (hovered_window && hovered_window_ignoring_moving_window)
5476
352
            break;
5477
376
    }
5478
5479
18.0k
    g.HoveredWindow = hovered_window;
5480
18.0k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5481
5482
18.0k
    if (g.MovingWindow)
5483
37
        g.MovingWindow->Viewport = moving_window_viewport;
5484
18.0k
}
5485
5486
bool ImGui::IsItemActive()
5487
36.0k
{
5488
36.0k
    ImGuiContext& g = *GImGui;
5489
36.0k
    if (g.ActiveId)
5490
282
        return g.ActiveId == g.LastItemData.ID;
5491
35.7k
    return false;
5492
36.0k
}
5493
5494
bool ImGui::IsItemActivated()
5495
0
{
5496
0
    ImGuiContext& g = *GImGui;
5497
0
    if (g.ActiveId)
5498
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5499
0
            return true;
5500
0
    return false;
5501
0
}
5502
5503
bool ImGui::IsItemDeactivated()
5504
0
{
5505
0
    ImGuiContext& g = *GImGui;
5506
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5507
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5508
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5509
0
}
5510
5511
bool ImGui::IsItemDeactivatedAfterEdit()
5512
0
{
5513
0
    ImGuiContext& g = *GImGui;
5514
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5515
0
}
5516
5517
// == GetItemID() == GetFocusID()
5518
bool ImGui::IsItemFocused()
5519
0
{
5520
0
    ImGuiContext& g = *GImGui;
5521
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5522
0
        return false;
5523
5524
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5525
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5526
0
    ImGuiWindow* window = g.CurrentWindow;
5527
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5528
0
        return false;
5529
5530
0
    return true;
5531
0
}
5532
5533
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5534
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5535
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5536
0
{
5537
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5538
0
}
5539
5540
bool ImGui::IsItemToggledOpen()
5541
0
{
5542
0
    ImGuiContext& g = *GImGui;
5543
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5544
0
}
5545
5546
bool ImGui::IsItemToggledSelection()
5547
0
{
5548
0
    ImGuiContext& g = *GImGui;
5549
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5550
0
}
5551
5552
bool ImGui::IsAnyItemHovered()
5553
0
{
5554
0
    ImGuiContext& g = *GImGui;
5555
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5556
0
}
5557
5558
bool ImGui::IsAnyItemActive()
5559
0
{
5560
0
    ImGuiContext& g = *GImGui;
5561
0
    return g.ActiveId != 0;
5562
0
}
5563
5564
bool ImGui::IsAnyItemFocused()
5565
0
{
5566
0
    ImGuiContext& g = *GImGui;
5567
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5568
0
}
5569
5570
bool ImGui::IsItemVisible()
5571
0
{
5572
0
    ImGuiContext& g = *GImGui;
5573
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5574
0
}
5575
5576
bool ImGui::IsItemEdited()
5577
0
{
5578
0
    ImGuiContext& g = *GImGui;
5579
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5580
0
}
5581
5582
// Allow next item to be overlapped by subsequent items.
5583
// This works by requiring HoveredId to match for two subsequent frames,
5584
// so if a following items overwrite it our interactions will naturally be disabled.
5585
void ImGui::SetNextItemAllowOverlap()
5586
0
{
5587
0
    ImGuiContext& g = *GImGui;
5588
0
    g.NextItemData.ItemFlags |= ImGuiItemflags_AllowOverlap;
5589
0
}
5590
5591
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
5592
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5593
// FIXME-LEGACY: Use SetNextItemAllowOverlap() *before* your item instead.
5594
void ImGui::SetItemAllowOverlap()
5595
{
5596
    ImGuiContext& g = *GImGui;
5597
    ImGuiID id = g.LastItemData.ID;
5598
    if (g.HoveredId == id)
5599
        g.HoveredIdAllowOverlap = true;
5600
    if (g.ActiveId == id) // Before we made this obsolete, most calls to SetItemAllowOverlap() used to avoid this path by testing g.ActiveId != id.
5601
        g.ActiveIdAllowOverlap = true;
5602
}
5603
#endif
5604
5605
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5606
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5607
17
{
5608
17
    ImGuiContext& g = *GImGui;
5609
17
    IM_ASSERT(g.ActiveId != 0);
5610
17
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5611
17
    g.ActiveIdUsingAllKeyboardKeys = true;
5612
17
    NavMoveRequestCancel();
5613
17
}
5614
5615
ImGuiID ImGui::GetItemID()
5616
0
{
5617
0
    ImGuiContext& g = *GImGui;
5618
0
    return g.LastItemData.ID;
5619
0
}
5620
5621
ImVec2 ImGui::GetItemRectMin()
5622
0
{
5623
0
    ImGuiContext& g = *GImGui;
5624
0
    return g.LastItemData.Rect.Min;
5625
0
}
5626
5627
ImVec2 ImGui::GetItemRectMax()
5628
0
{
5629
0
    ImGuiContext& g = *GImGui;
5630
0
    return g.LastItemData.Rect.Max;
5631
0
}
5632
5633
ImVec2 ImGui::GetItemRectSize()
5634
0
{
5635
0
    ImGuiContext& g = *GImGui;
5636
0
    return g.LastItemData.Rect.GetSize();
5637
0
}
5638
5639
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5640
9.51k
{
5641
9.51k
    ImGuiContext& g = *GImGui;
5642
9.51k
    ImGuiWindow* parent_window = g.CurrentWindow;
5643
5644
9.51k
    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
5645
9.51k
    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5646
5647
    // Size
5648
9.51k
    const ImVec2 content_avail = GetContentRegionAvail();
5649
9.51k
    ImVec2 size = ImFloor(size_arg);
5650
9.51k
    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5651
9.51k
    if (size.x <= 0.0f)
5652
8.49k
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5653
9.51k
    if (size.y <= 0.0f)
5654
8.44k
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5655
9.51k
    SetNextWindowSize(size);
5656
5657
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5658
9.51k
    const char* temp_window_name;
5659
9.51k
    if (name)
5660
9.51k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5661
0
    else
5662
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5663
5664
9.51k
    const float backup_border_size = g.Style.ChildBorderSize;
5665
9.51k
    if (!border)
5666
4.51k
        g.Style.ChildBorderSize = 0.0f;
5667
9.51k
    bool ret = Begin(temp_window_name, NULL, flags);
5668
9.51k
    g.Style.ChildBorderSize = backup_border_size;
5669
5670
9.51k
    ImGuiWindow* child_window = g.CurrentWindow;
5671
9.51k
    child_window->ChildId = id;
5672
9.51k
    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5673
5674
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5675
    // While this is not really documented/defined, it seems that the expected thing to do.
5676
9.51k
    if (child_window->BeginCount == 1)
5677
9.51k
        parent_window->DC.CursorPos = child_window->Pos;
5678
5679
    // Process navigation-in immediately so NavInit can run on first frame
5680
    // Can enter a child if (A) it has navigatable items or (B) it can be scrolled.
5681
9.51k
    const ImGuiID temp_id_for_activation = ImHashStr("##Child", 0, id);
5682
9.51k
    if (g.ActiveId == temp_id_for_activation)
5683
12
        ClearActiveID();
5684
9.51k
    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavWindowHasScrollY))
5685
13
    {
5686
13
        FocusWindow(child_window);
5687
13
        NavInitWindow(child_window, false);
5688
13
        SetActiveID(temp_id_for_activation, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5689
13
        g.ActiveIdSource = g.NavInputSource;
5690
13
    }
5691
9.51k
    return ret;
5692
9.51k
}
5693
5694
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5695
9.51k
{
5696
9.51k
    ImGuiWindow* window = GetCurrentWindow();
5697
9.51k
    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5698
9.51k
}
5699
5700
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5701
0
{
5702
0
    IM_ASSERT(id != 0);
5703
0
    return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5704
0
}
5705
5706
void ImGui::EndChild()
5707
9.51k
{
5708
9.51k
    ImGuiContext& g = *GImGui;
5709
9.51k
    ImGuiWindow* window = g.CurrentWindow;
5710
5711
9.51k
    IM_ASSERT(g.WithinEndChild == false);
5712
9.51k
    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5713
5714
9.51k
    g.WithinEndChild = true;
5715
9.51k
    if (window->BeginCount > 1)
5716
0
    {
5717
0
        End();
5718
0
    }
5719
9.51k
    else
5720
9.51k
    {
5721
9.51k
        ImVec2 sz = window->Size;
5722
9.51k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5723
8.49k
            sz.x = ImMax(4.0f, sz.x);
5724
9.51k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5725
8.44k
            sz.y = ImMax(4.0f, sz.y);
5726
9.51k
        End();
5727
5728
9.51k
        ImGuiWindow* parent_window = g.CurrentWindow;
5729
9.51k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5730
9.51k
        ItemSize(sz);
5731
9.51k
        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavWindowHasScrollY) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5732
8.69k
        {
5733
8.69k
            ItemAdd(bb, window->ChildId);
5734
8.69k
            RenderNavHighlight(bb, window->ChildId);
5735
5736
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5737
8.69k
            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5738
7.02k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5739
8.69k
        }
5740
826
        else
5741
826
        {
5742
            // Not navigable into
5743
826
            ItemAdd(bb, 0);
5744
5745
            // But when flattened we directly reach items, adjust active layer mask accordingly
5746
826
            if (window->Flags & ImGuiWindowFlags_NavFlattened)
5747
0
                parent_window->DC.NavLayersActiveMaskNext |= window->DC.NavLayersActiveMaskNext;
5748
826
        }
5749
9.51k
        if (g.HoveredWindow == window)
5750
1
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5751
9.51k
    }
5752
9.51k
    g.WithinEndChild = false;
5753
9.51k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5754
9.51k
}
5755
5756
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5757
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5758
0
{
5759
0
    ImGuiContext& g = *GImGui;
5760
0
    const ImGuiStyle& style = g.Style;
5761
0
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5762
0
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5763
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5764
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5765
0
    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5766
0
    PopStyleVar(3);
5767
0
    PopStyleColor();
5768
0
    return ret;
5769
0
}
5770
5771
void ImGui::EndChildFrame()
5772
0
{
5773
0
    EndChild();
5774
0
}
5775
5776
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5777
30
{
5778
30
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5779
30
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5780
30
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5781
30
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5782
30
}
5783
5784
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5785
45.5k
{
5786
45.5k
    ImGuiContext& g = *GImGui;
5787
45.5k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5788
45.5k
}
5789
5790
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5791
45.5k
{
5792
45.5k
    ImGuiID id = ImHashStr(name);
5793
45.5k
    return FindWindowByID(id);
5794
45.5k
}
5795
5796
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5797
0
{
5798
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5799
0
    window->ViewportPos = main_viewport->Pos;
5800
0
    if (settings->ViewportId)
5801
0
    {
5802
0
        window->ViewportId = settings->ViewportId;
5803
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5804
0
    }
5805
0
    window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5806
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5807
0
        window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
5808
0
    window->Collapsed = settings->Collapsed;
5809
0
    window->DockId = settings->DockId;
5810
0
    window->DockOrder = settings->DockOrder;
5811
0
}
5812
5813
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5814
45.5k
{
5815
45.5k
    ImGuiContext& g = *GImGui;
5816
5817
45.5k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5818
45.5k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5819
45.5k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5820
2
    {
5821
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5822
2
        g.WindowsFocusOrder.push_back(window);
5823
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5824
2
    }
5825
45.5k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5826
0
    {
5827
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5828
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5829
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5830
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5831
0
        window->FocusOrder = -1;
5832
0
    }
5833
45.5k
    window->IsExplicitChild = new_is_explicit_child;
5834
45.5k
}
5835
5836
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5837
3
{
5838
    // Initial window state with e.g. default/arbitrary window position
5839
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5840
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5841
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5842
3
    window->ViewportPos = main_viewport->Pos;
5843
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5844
5845
3
    if (settings != NULL)
5846
0
    {
5847
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5848
0
        ApplyWindowSettings(window, settings);
5849
0
    }
5850
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5851
5852
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5853
0
    {
5854
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5855
0
        window->AutoFitOnlyGrows = false;
5856
0
    }
5857
3
    else
5858
3
    {
5859
3
        if (window->Size.x <= 0.0f)
5860
3
            window->AutoFitFramesX = 2;
5861
3
        if (window->Size.y <= 0.0f)
5862
3
            window->AutoFitFramesY = 2;
5863
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5864
3
    }
5865
3
}
5866
5867
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5868
3
{
5869
    // Create window the first time
5870
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5871
3
    ImGuiContext& g = *GImGui;
5872
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5873
3
    window->Flags = flags;
5874
3
    g.WindowsById.SetVoidPtr(window->ID, window);
5875
5876
3
    ImGuiWindowSettings* settings = NULL;
5877
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5878
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5879
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5880
5881
3
    InitOrLoadWindowSettings(window, settings);
5882
5883
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5884
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5885
3
    else
5886
3
        g.Windows.push_back(window);
5887
5888
3
    return window;
5889
3
}
5890
5891
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5892
0
{
5893
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5894
0
}
5895
5896
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5897
72.0k
{
5898
72.0k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5899
72.0k
}
5900
5901
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5902
91.0k
{
5903
91.0k
    ImGuiContext& g = *GImGui;
5904
91.0k
    ImVec2 new_size = size_desired;
5905
91.0k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5906
0
    {
5907
        // Using -1,-1 on either X/Y axis to preserve the current size.
5908
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5909
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5910
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5911
0
        if (g.NextWindowData.SizeCallback)
5912
0
        {
5913
0
            ImGuiSizeCallbackData data;
5914
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5915
0
            data.Pos = window->Pos;
5916
0
            data.CurrentSize = window->SizeFull;
5917
0
            data.DesiredSize = new_size;
5918
0
            g.NextWindowData.SizeCallback(&data);
5919
0
            new_size = data.DesiredSize;
5920
0
        }
5921
0
        new_size.x = IM_FLOOR(new_size.x);
5922
0
        new_size.y = IM_FLOOR(new_size.y);
5923
0
    }
5924
5925
    // Minimum size
5926
91.0k
    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
5927
72.0k
    {
5928
72.0k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5929
72.0k
        new_size = ImMax(new_size, g.Style.WindowMinSize);
5930
72.0k
        const float minimum_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f);
5931
72.0k
        new_size.y = ImMax(new_size.y, minimum_height); // Reduce artifacts with very small windows
5932
72.0k
    }
5933
91.0k
    return new_size;
5934
91.0k
}
5935
5936
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5937
45.5k
{
5938
45.5k
    bool preserve_old_content_sizes = false;
5939
45.5k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5940
8.49k
        preserve_old_content_sizes = true;
5941
37.0k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5942
952
        preserve_old_content_sizes = true;
5943
45.5k
    if (preserve_old_content_sizes)
5944
9.44k
    {
5945
9.44k
        *content_size_current = window->ContentSize;
5946
9.44k
        *content_size_ideal = window->ContentSizeIdeal;
5947
9.44k
        return;
5948
9.44k
    }
5949
5950
36.0k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
5951
36.0k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
5952
36.0k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
5953
36.0k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
5954
36.0k
}
5955
5956
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
5957
45.5k
{
5958
45.5k
    ImGuiContext& g = *GImGui;
5959
45.5k
    ImGuiStyle& style = g.Style;
5960
45.5k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
5961
45.5k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
5962
45.5k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
5963
45.5k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
5964
45.5k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
5965
0
    {
5966
        // Tooltip always resize
5967
0
        return size_desired;
5968
0
    }
5969
45.5k
    else
5970
45.5k
    {
5971
        // Maximum window size is determined by the viewport size or monitor size
5972
45.5k
        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
5973
45.5k
        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
5974
45.5k
        ImVec2 size_min = style.WindowMinSize;
5975
45.5k
        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5976
0
            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
5977
5978
45.5k
        ImVec2 avail_size = window->Viewport->WorkSize;
5979
45.5k
        if (window->ViewportOwned)
5980
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
5981
45.5k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
5982
45.5k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
5983
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
5984
45.5k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
5985
5986
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
5987
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
5988
45.5k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5989
45.5k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
5990
45.5k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
5991
45.5k
        if (will_have_scrollbar_x)
5992
9.51k
            size_auto_fit.y += style.ScrollbarSize;
5993
45.5k
        if (will_have_scrollbar_y)
5994
8.74k
            size_auto_fit.x += style.ScrollbarSize;
5995
45.5k
        return size_auto_fit;
5996
45.5k
    }
5997
45.5k
}
5998
5999
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
6000
0
{
6001
0
    ImVec2 size_contents_current;
6002
0
    ImVec2 size_contents_ideal;
6003
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
6004
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
6005
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6006
0
    return size_final;
6007
0
}
6008
6009
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
6010
37.0k
{
6011
37.0k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
6012
0
        return ImGuiCol_PopupBg;
6013
37.0k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
6014
9.51k
        return ImGuiCol_ChildBg;
6015
27.5k
    return ImGuiCol_WindowBg;
6016
37.0k
}
6017
6018
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
6019
0
{
6020
0
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
6021
0
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
6022
0
    ImVec2 size_expected = pos_max - pos_min;
6023
0
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
6024
0
    *out_pos = pos_min;
6025
0
    if (corner_norm.x == 0.0f)
6026
0
        out_pos->x -= (size_constrained.x - size_expected.x);
6027
0
    if (corner_norm.y == 0.0f)
6028
0
        out_pos->y -= (size_constrained.y - size_expected.y);
6029
0
    *out_size = size_constrained;
6030
0
}
6031
6032
// Data for resizing from corner
6033
struct ImGuiResizeGripDef
6034
{
6035
    ImVec2  CornerPosN;
6036
    ImVec2  InnerDir;
6037
    int     AngleMin12, AngleMax12;
6038
};
6039
static const ImGuiResizeGripDef resize_grip_def[4] =
6040
{
6041
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
6042
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
6043
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
6044
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
6045
};
6046
6047
// Data for resizing from borders
6048
struct ImGuiResizeBorderDef
6049
{
6050
    ImVec2 InnerDir;
6051
    ImVec2 SegmentN1, SegmentN2;
6052
    float  OuterAngle;
6053
};
6054
static const ImGuiResizeBorderDef resize_border_def[4] =
6055
{
6056
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
6057
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
6058
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
6059
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
6060
};
6061
6062
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
6063
0
{
6064
0
    ImRect rect = window->Rect();
6065
0
    if (thickness == 0.0f)
6066
0
        rect.Max -= ImVec2(1, 1);
6067
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
6068
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
6069
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
6070
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
6071
0
    IM_ASSERT(0);
6072
0
    return ImRect();
6073
0
}
6074
6075
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
6076
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
6077
0
{
6078
0
    IM_ASSERT(n >= 0 && n < 4);
6079
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6080
0
    id = ImHashStr("#RESIZE", 0, id);
6081
0
    id = ImHashData(&n, sizeof(int), id);
6082
0
    return id;
6083
0
}
6084
6085
// Borders (Left, Right, Up, Down)
6086
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
6087
0
{
6088
0
    IM_ASSERT(dir >= 0 && dir < 4);
6089
0
    int n = (int)dir + 4;
6090
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
6091
0
    id = ImHashStr("#RESIZE", 0, id);
6092
0
    id = ImHashData(&n, sizeof(int), id);
6093
0
    return id;
6094
0
}
6095
6096
// Handle resize for: Resize Grips, Borders, Gamepad
6097
// Return true when using auto-fit (double-click on resize grip)
6098
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
6099
37.0k
{
6100
37.0k
    ImGuiContext& g = *GImGui;
6101
37.0k
    ImGuiWindowFlags flags = window->Flags;
6102
6103
37.0k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6104
9.51k
        return false;
6105
27.5k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
6106
18.0k
        return false;
6107
6108
9.51k
    bool ret_auto_fit = false;
6109
9.51k
    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
6110
9.51k
    const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6111
9.51k
    const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
6112
9.51k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
6113
6114
9.51k
    ImRect clamp_rect = visibility_rect;
6115
9.51k
    const bool window_move_from_title_bar = g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar);
6116
9.51k
    if (window_move_from_title_bar)
6117
0
        clamp_rect.Min.y -= window->TitleBarHeight();
6118
6119
9.51k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
6120
9.51k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
6121
6122
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
6123
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
6124
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
6125
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
6126
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
6127
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
6128
9.51k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
6129
9.51k
    if (clip_with_viewport_rect)
6130
9.51k
        window->ClipRect = window->Viewport->GetMainRect();
6131
6132
    // Resize grips and borders are on layer 1
6133
9.51k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6134
6135
    // Manual resize grips
6136
9.51k
    PushID("#RESIZE");
6137
19.0k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6138
9.51k
    {
6139
9.51k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
6140
9.51k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
6141
6142
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
6143
9.51k
        bool hovered, held;
6144
9.51k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
6145
9.51k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
6146
9.51k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
6147
9.51k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
6148
9.51k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
6149
9.51k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6150
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
6151
9.51k
        if (hovered || held)
6152
0
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
6153
6154
9.51k
        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
6155
0
        {
6156
            // Manual auto-fit when double-clicking
6157
0
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
6158
0
            ret_auto_fit = true;
6159
0
            ClearActiveID();
6160
0
        }
6161
9.51k
        else if (held)
6162
0
        {
6163
            // Resize from any of the four corners
6164
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
6165
0
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? clamp_rect.Min.x : -FLT_MAX, (def.CornerPosN.y == 1.0f || (def.CornerPosN.y == 0.0f && window_move_from_title_bar)) ? clamp_rect.Min.y : -FLT_MAX);
6166
0
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? clamp_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? clamp_rect.Max.y : +FLT_MAX);
6167
0
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
6168
0
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
6169
0
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
6170
0
        }
6171
6172
        // Only lower-left grip is visible before hovering/activating
6173
9.51k
        if (resize_grip_n == 0 || held || hovered)
6174
9.51k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
6175
9.51k
    }
6176
9.51k
    for (int border_n = 0; border_n < resize_border_count; border_n++)
6177
0
    {
6178
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
6179
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
6180
6181
0
        bool hovered, held;
6182
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
6183
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
6184
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
6185
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
6186
        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
6187
0
        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
6188
0
        {
6189
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
6190
0
            if (held)
6191
0
                *border_held = border_n;
6192
0
        }
6193
0
        if (held)
6194
0
        {
6195
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? clamp_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down || (border_n == ImGuiDir_Up && window_move_from_title_bar) ? clamp_rect.Min.y : -FLT_MAX);
6196
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left ? clamp_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? clamp_rect.Max.y : +FLT_MAX);
6197
0
            ImVec2 border_target = window->Pos;
6198
0
            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
6199
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
6200
0
            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
6201
0
        }
6202
0
    }
6203
9.51k
    PopID();
6204
6205
    // Restore nav layer
6206
9.51k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6207
6208
    // Navigation resize (keyboard/gamepad)
6209
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6210
    // Not even sure the callback works here.
6211
9.51k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6212
0
    {
6213
0
        ImVec2 nav_resize_dir;
6214
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6215
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6216
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6217
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6218
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6219
0
        {
6220
0
            const float NAV_RESIZE_SPEED = 600.0f;
6221
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6222
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6223
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, clamp_rect.Min - window->Pos - window->Size); // We need Pos+Size >= clmap_rect.Min, so Size >= clmap_rect.Min - Pos, so size_delta >= clmap_rect.Min - window->Pos - window->Size
6224
0
            g.NavWindowingToggleLayer = false;
6225
0
            g.NavDisableMouseHover = true;
6226
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6227
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaSize);
6228
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6229
0
            {
6230
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6231
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6232
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6233
0
            }
6234
0
        }
6235
0
    }
6236
6237
    // Apply back modified position/size to window
6238
9.51k
    if (size_target.x != FLT_MAX)
6239
0
    {
6240
0
        window->SizeFull = size_target;
6241
0
        MarkIniSettingsDirty(window);
6242
0
    }
6243
9.51k
    if (pos_target.x != FLT_MAX)
6244
0
    {
6245
0
        window->Pos = ImFloor(pos_target);
6246
0
        MarkIniSettingsDirty(window);
6247
0
    }
6248
6249
9.51k
    window->Size = window->SizeFull;
6250
9.51k
    return ret_auto_fit;
6251
27.5k
}
6252
6253
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6254
36.0k
{
6255
36.0k
    ImGuiContext& g = *GImGui;
6256
36.0k
    ImVec2 size_for_clamping = window->Size;
6257
36.0k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6258
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6259
36.0k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6260
36.0k
}
6261
6262
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6263
37.0k
{
6264
37.0k
    ImGuiContext& g = *GImGui;
6265
37.0k
    float rounding = window->WindowRounding;
6266
37.0k
    float border_size = window->WindowBorderSize;
6267
37.0k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6268
32.5k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6269
6270
37.0k
    int border_held = window->ResizeBorderHeld;
6271
37.0k
    if (border_held != -1)
6272
0
    {
6273
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_held];
6274
0
        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
6275
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6276
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6277
0
        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
6278
0
    }
6279
37.0k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6280
0
    {
6281
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6282
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6283
0
    }
6284
37.0k
}
6285
6286
// Draw background and borders
6287
// Draw and handle scrollbars
6288
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6289
45.5k
{
6290
45.5k
    ImGuiContext& g = *GImGui;
6291
45.5k
    ImGuiStyle& style = g.Style;
6292
45.5k
    ImGuiWindowFlags flags = window->Flags;
6293
6294
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6295
45.5k
    IM_ASSERT(window->BeginCount == 0);
6296
45.5k
    window->SkipItems = false;
6297
6298
    // Draw window + handle manual resize
6299
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6300
45.5k
    const float window_rounding = window->WindowRounding;
6301
45.5k
    const float window_border_size = window->WindowBorderSize;
6302
45.5k
    if (window->Collapsed)
6303
8.49k
    {
6304
        // Title bar only
6305
8.49k
        const float backup_border_size = style.FrameBorderSize;
6306
8.49k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6307
8.49k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6308
8.49k
        if (window->ViewportOwned)
6309
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6310
8.49k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6311
8.49k
        g.Style.FrameBorderSize = backup_border_size;
6312
8.49k
    }
6313
37.0k
    else
6314
37.0k
    {
6315
        // Window background
6316
37.0k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6317
37.0k
        {
6318
37.0k
            bool is_docking_transparent_payload = false;
6319
37.0k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6320
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6321
0
                    is_docking_transparent_payload = true;
6322
6323
37.0k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6324
37.0k
            if (window->ViewportOwned)
6325
0
            {
6326
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6327
0
                if (is_docking_transparent_payload)
6328
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6329
0
            }
6330
37.0k
            else
6331
37.0k
            {
6332
                // Adjust alpha. For docking
6333
37.0k
                bool override_alpha = false;
6334
37.0k
                float alpha = 1.0f;
6335
37.0k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6336
0
                {
6337
0
                    alpha = g.NextWindowData.BgAlphaVal;
6338
0
                    override_alpha = true;
6339
0
                }
6340
37.0k
                if (is_docking_transparent_payload)
6341
0
                {
6342
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6343
0
                    override_alpha = true;
6344
0
                }
6345
37.0k
                if (override_alpha)
6346
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6347
37.0k
            }
6348
6349
            // Render, for docked windows and host windows we ensure bg goes before decorations
6350
37.0k
            if (window->DockIsActive)
6351
0
                window->DockNode->LastBgColor = bg_col;
6352
37.0k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6353
37.0k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6354
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6355
37.0k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6356
37.0k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6357
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6358
37.0k
        }
6359
37.0k
        if (window->DockIsActive)
6360
0
            window->DockNode->IsBgDrawnThisFrame = true;
6361
6362
        // Title bar
6363
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6364
        // in order for their pos/size to be matching their undocking state.)
6365
37.0k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6366
27.5k
        {
6367
27.5k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6368
27.5k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6369
27.5k
        }
6370
6371
        // Menu bar
6372
37.0k
        if (flags & ImGuiWindowFlags_MenuBar)
6373
0
        {
6374
0
            ImRect menu_bar_rect = window->MenuBarRect();
6375
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6376
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6377
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6378
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6379
0
        }
6380
6381
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6382
37.0k
        ImGuiDockNode* node = window->DockNode;
6383
37.0k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6384
0
        {
6385
0
            float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
6386
0
            float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
6387
0
            ImVec2 p = node->Pos;
6388
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6389
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6390
0
            KeepAliveID(unhide_id);
6391
0
            bool hovered, held;
6392
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6393
0
                node->WantHiddenTabBarToggle = true;
6394
0
            else if (held && IsMouseDragging(0))
6395
0
                StartMouseMovingWindowOrNode(window, node, true);
6396
6397
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6398
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6399
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6400
0
        }
6401
6402
        // Scrollbars
6403
37.0k
        if (window->ScrollbarX)
6404
9.51k
            Scrollbar(ImGuiAxis_X);
6405
37.0k
        if (window->ScrollbarY)
6406
18.1k
            Scrollbar(ImGuiAxis_Y);
6407
6408
        // Render resize grips (after their input handling so we don't have a frame of latency)
6409
37.0k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6410
27.5k
        {
6411
55.0k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6412
27.5k
            {
6413
27.5k
                const ImU32 col = resize_grip_col[resize_grip_n];
6414
27.5k
                if ((col & IM_COL32_A_MASK) == 0)
6415
18.0k
                    continue;
6416
9.51k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6417
9.51k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6418
9.51k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6419
9.51k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6420
9.51k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6421
9.51k
                window->DrawList->PathFillConvex(col);
6422
9.51k
            }
6423
27.5k
        }
6424
6425
        // Borders (for dock node host they will be rendered over after the tab bar)
6426
37.0k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6427
37.0k
            RenderWindowOuterBorders(window);
6428
37.0k
    }
6429
45.5k
}
6430
6431
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6432
// Render title text, collapse button, close button
6433
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6434
36.0k
{
6435
36.0k
    ImGuiContext& g = *GImGui;
6436
36.0k
    ImGuiStyle& style = g.Style;
6437
36.0k
    ImGuiWindowFlags flags = window->Flags;
6438
6439
36.0k
    const bool has_close_button = (p_open != NULL);
6440
36.0k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6441
6442
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6443
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6444
36.0k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6445
36.0k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6446
36.0k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6447
6448
    // Layout buttons
6449
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6450
36.0k
    float pad_l = style.FramePadding.x;
6451
36.0k
    float pad_r = style.FramePadding.x;
6452
36.0k
    float button_sz = g.FontSize;
6453
36.0k
    ImVec2 close_button_pos;
6454
36.0k
    ImVec2 collapse_button_pos;
6455
36.0k
    if (has_close_button)
6456
0
    {
6457
0
        pad_r += button_sz;
6458
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6459
0
    }
6460
36.0k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6461
0
    {
6462
0
        pad_r += button_sz;
6463
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6464
0
    }
6465
36.0k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6466
36.0k
    {
6467
36.0k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
6468
36.0k
        pad_l += button_sz;
6469
36.0k
    }
6470
6471
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6472
36.0k
    if (has_collapse_button)
6473
36.0k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6474
24
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6475
6476
    // Close button
6477
36.0k
    if (has_close_button)
6478
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6479
0
            *p_open = false;
6480
6481
36.0k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6482
36.0k
    g.CurrentItemFlags = item_flags_backup;
6483
6484
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6485
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6486
36.0k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6487
36.0k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6488
6489
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6490
    // while uncentered title text will still reach edges correctly.
6491
36.0k
    if (pad_l > style.FramePadding.x)
6492
36.0k
        pad_l += g.Style.ItemInnerSpacing.x;
6493
36.0k
    if (pad_r > style.FramePadding.x)
6494
0
        pad_r += g.Style.ItemInnerSpacing.x;
6495
36.0k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6496
0
    {
6497
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6498
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6499
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6500
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6501
0
    }
6502
6503
36.0k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6504
36.0k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6505
36.0k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6506
0
    {
6507
0
        ImVec2 marker_pos;
6508
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6509
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6510
0
        if (marker_pos.x > layout_r.Min.x)
6511
0
        {
6512
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6513
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6514
0
        }
6515
0
    }
6516
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6517
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6518
36.0k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6519
36.0k
}
6520
6521
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6522
45.5k
{
6523
45.5k
    window->ParentWindow = parent_window;
6524
45.5k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6525
45.5k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6526
9.51k
    {
6527
9.51k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6528
9.51k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6529
9.51k
            window->RootWindow = parent_window->RootWindow;
6530
9.51k
    }
6531
45.5k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6532
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6533
45.5k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6534
9.51k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6535
45.5k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6536
0
    {
6537
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6538
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6539
0
    }
6540
45.5k
}
6541
6542
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6543
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6544
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6545
// - WindowA            // FindBlockingModal() returns Modal1
6546
//   - WindowB          //                  .. returns Modal1
6547
//   - Modal1           //                  .. returns Modal2
6548
//      - WindowC       //                  .. returns Modal2
6549
//          - WindowD   //                  .. returns Modal2
6550
//          - Modal2    //                  .. returns Modal2
6551
//            - WindowE //                  .. returns NULL
6552
// Notes:
6553
// - FindBlockingModal(NULL) == NULL is generally equivalent to GetTopMostPopupModal() == NULL.
6554
//   Only difference is here we check for ->Active/WasActive but it may be unecessary.
6555
ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6556
26
{
6557
26
    ImGuiContext& g = *GImGui;
6558
26
    if (g.OpenPopupStack.Size <= 0)
6559
26
        return NULL;
6560
6561
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6562
0
    for (int i = 0; i < g.OpenPopupStack.Size; i++)
6563
0
    {
6564
0
        ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
6565
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6566
0
            continue;
6567
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6568
0
            continue;
6569
0
        if (window == NULL)                                         // FindBlockingModal(NULL) test for if FocusWindow(NULL) is naturally possible via a mouse click.
6570
0
            return popup_window;
6571
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window may be over modal
6572
0
            continue;
6573
0
        return popup_window;                                        // Place window right below first block modal
6574
0
    }
6575
0
    return NULL;
6576
0
}
6577
6578
// Push a new Dear ImGui window to add widgets to.
6579
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6580
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6581
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6582
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6583
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6584
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6585
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6586
45.5k
{
6587
45.5k
    ImGuiContext& g = *GImGui;
6588
45.5k
    const ImGuiStyle& style = g.Style;
6589
45.5k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6590
45.5k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6591
45.5k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6592
6593
    // Find or create
6594
45.5k
    ImGuiWindow* window = FindWindowByName(name);
6595
45.5k
    const bool window_just_created = (window == NULL);
6596
45.5k
    if (window_just_created)
6597
3
        window = CreateNewWindow(name, flags);
6598
6599
    // Automatically disable manual moving/resizing when NoInputs is set
6600
45.5k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6601
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6602
6603
45.5k
    if (flags & ImGuiWindowFlags_NavFlattened)
6604
45.5k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6605
6606
45.5k
    const int current_frame = g.FrameCount;
6607
45.5k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6608
45.5k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6609
6610
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6611
45.5k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6612
45.5k
    if (flags & ImGuiWindowFlags_Popup)
6613
0
    {
6614
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6615
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6616
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6617
0
    }
6618
6619
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6620
45.5k
    const bool window_was_appearing = window->Appearing;
6621
45.5k
    if (first_begin_of_the_frame)
6622
45.5k
    {
6623
45.5k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6624
45.5k
        window->Appearing = window_just_activated_by_user;
6625
45.5k
        if (window->Appearing)
6626
15
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6627
45.5k
        window->FlagsPreviousFrame = window->Flags;
6628
45.5k
        window->Flags = (ImGuiWindowFlags)flags;
6629
45.5k
        window->LastFrameActive = current_frame;
6630
45.5k
        window->LastTimeActive = (float)g.Time;
6631
45.5k
        window->BeginOrderWithinParent = 0;
6632
45.5k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6633
45.5k
    }
6634
0
    else
6635
0
    {
6636
0
        flags = window->Flags;
6637
0
    }
6638
6639
    // Docking
6640
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6641
45.5k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6642
45.5k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6643
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6644
45.5k
    if (first_begin_of_the_frame)
6645
45.5k
    {
6646
45.5k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6647
45.5k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6648
45.5k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6649
45.5k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6650
45.5k
        if (has_dock_node || new_auto_dock_node)
6651
0
        {
6652
0
            BeginDocked(window, p_open);
6653
0
            flags = window->Flags;
6654
0
            if (window->DockIsActive)
6655
0
            {
6656
0
                IM_ASSERT(window->DockNode != NULL);
6657
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6658
0
            }
6659
6660
            // Amend the Appearing flag
6661
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6662
0
            {
6663
0
                window->Appearing = true;
6664
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6665
0
            }
6666
0
        }
6667
45.5k
        else
6668
45.5k
        {
6669
45.5k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6670
45.5k
        }
6671
45.5k
    }
6672
6673
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6674
45.5k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6675
45.5k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6676
45.5k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6677
6678
    // We allow window memory to be compacted so recreate the base stack when needed.
6679
45.5k
    if (window->IDStack.Size == 0)
6680
0
        window->IDStack.push_back(window->ID);
6681
6682
    // Add to stack
6683
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6684
45.5k
    g.CurrentWindow = window;
6685
45.5k
    ImGuiWindowStackData window_stack_data;
6686
45.5k
    window_stack_data.Window = window;
6687
45.5k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6688
45.5k
    window_stack_data.StackSizesOnBegin.SetToContextState(&g);
6689
45.5k
    g.CurrentWindowStack.push_back(window_stack_data);
6690
45.5k
    if (flags & ImGuiWindowFlags_ChildMenu)
6691
0
        g.BeginMenuCount++;
6692
6693
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6694
45.5k
    if (first_begin_of_the_frame)
6695
45.5k
    {
6696
45.5k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6697
45.5k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6698
45.5k
    }
6699
6700
    // Add to focus scope stack
6701
45.5k
    PushFocusScope(window->ID);
6702
45.5k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6703
45.5k
    g.CurrentWindow = NULL;
6704
6705
    // Add to popup stack
6706
45.5k
    if (flags & ImGuiWindowFlags_Popup)
6707
0
    {
6708
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6709
0
        popup_ref.Window = window;
6710
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6711
0
        g.BeginPopupStack.push_back(popup_ref);
6712
0
        window->PopupId = popup_ref.PopupId;
6713
0
    }
6714
6715
    // Process SetNextWindow***() calls
6716
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6717
45.5k
    bool window_pos_set_by_api = false;
6718
45.5k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6719
45.5k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6720
0
    {
6721
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6722
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6723
0
        {
6724
            // May be processed on the next frame if this is our first frame and we are measuring size
6725
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6726
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6727
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6728
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6729
0
        }
6730
0
        else
6731
0
        {
6732
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6733
0
        }
6734
0
    }
6735
45.5k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6736
27.5k
    {
6737
27.5k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6738
27.5k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6739
27.5k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6740
27.5k
    }
6741
45.5k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6742
0
    {
6743
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6744
0
        {
6745
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6746
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6747
0
        }
6748
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6749
0
        {
6750
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6751
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6752
0
        }
6753
0
    }
6754
45.5k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6755
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6756
45.5k
    else if (first_begin_of_the_frame)
6757
45.5k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6758
45.5k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6759
0
        window->WindowClass = g.NextWindowData.WindowClass;
6760
45.5k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6761
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6762
45.5k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6763
0
        FocusWindow(window);
6764
45.5k
    if (window->Appearing)
6765
15
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6766
6767
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6768
45.5k
    if (first_begin_of_the_frame)
6769
45.5k
    {
6770
        // Initialize
6771
45.5k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6772
45.5k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6773
45.5k
        window->Active = true;
6774
45.5k
        window->HasCloseButton = (p_open != NULL);
6775
45.5k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6776
45.5k
        window->IDStack.resize(1);
6777
45.5k
        window->DrawList->_ResetForNewFrame();
6778
45.5k
        window->DC.CurrentTableIdx = -1;
6779
45.5k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6780
0
        {
6781
0
            window->DrawList->ChannelsSplit(2);
6782
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6783
0
        }
6784
6785
        // Restore buffer capacity when woken from a compacted state, to avoid
6786
45.5k
        if (window->MemoryCompacted)
6787
0
            GcAwakeTransientWindowBuffers(window);
6788
6789
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6790
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6791
45.5k
        bool window_title_visible_elsewhere = false;
6792
45.5k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6793
0
            window_title_visible_elsewhere = true;
6794
45.5k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6795
0
            window_title_visible_elsewhere = true;
6796
45.5k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6797
0
        {
6798
0
            size_t buf_len = (size_t)window->NameBufLen;
6799
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6800
0
            window->NameBufLen = (int)buf_len;
6801
0
        }
6802
6803
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6804
6805
        // Update contents size from last frame for auto-fitting (or use explicit size)
6806
45.5k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6807
6808
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6809
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6810
        // it has a single usage before this code block and may be set below before it is finally checked.
6811
45.5k
        if (window->HiddenFramesCanSkipItems > 0)
6812
952
            window->HiddenFramesCanSkipItems--;
6813
45.5k
        if (window->HiddenFramesCannotSkipItems > 0)
6814
2
            window->HiddenFramesCannotSkipItems--;
6815
45.5k
        if (window->HiddenFramesForRenderOnly > 0)
6816
0
            window->HiddenFramesForRenderOnly--;
6817
6818
        // Hide new windows for one frame until they calculate their size
6819
45.5k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6820
1
            window->HiddenFramesCannotSkipItems = 1;
6821
6822
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6823
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6824
45.5k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6825
0
        {
6826
0
            window->HiddenFramesCannotSkipItems = 1;
6827
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6828
0
            {
6829
0
                if (!window_size_x_set_by_api)
6830
0
                    window->Size.x = window->SizeFull.x = 0.f;
6831
0
                if (!window_size_y_set_by_api)
6832
0
                    window->Size.y = window->SizeFull.y = 0.f;
6833
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6834
0
            }
6835
0
        }
6836
6837
        // SELECT VIEWPORT
6838
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6839
6840
45.5k
        WindowSelectViewport(window);
6841
45.5k
        SetCurrentViewport(window, window->Viewport);
6842
45.5k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6843
45.5k
        SetCurrentWindow(window);
6844
45.5k
        flags = window->Flags;
6845
6846
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6847
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6848
6849
45.5k
        if (flags & ImGuiWindowFlags_ChildWindow)
6850
9.51k
            window->WindowBorderSize = style.ChildBorderSize;
6851
36.0k
        else
6852
36.0k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6853
45.5k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
6854
4.51k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6855
41.0k
        else
6856
41.0k
            window->WindowPadding = style.WindowPadding;
6857
6858
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6859
45.5k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6860
45.5k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6861
6862
45.5k
        bool use_current_size_for_scrollbar_x = window_just_created;
6863
45.5k
        bool use_current_size_for_scrollbar_y = window_just_created;
6864
6865
        // Collapse window by double-clicking on title bar
6866
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6867
45.5k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
6868
36.0k
        {
6869
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
6870
36.0k
            ImRect title_bar_rect = window->TitleBarRect();
6871
36.0k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
6872
1
                window->WantCollapseToggle = true;
6873
36.0k
            if (window->WantCollapseToggle)
6874
25
            {
6875
25
                window->Collapsed = !window->Collapsed;
6876
25
                if (!window->Collapsed)
6877
12
                    use_current_size_for_scrollbar_y = true;
6878
25
                MarkIniSettingsDirty(window);
6879
25
            }
6880
36.0k
        }
6881
9.51k
        else
6882
9.51k
        {
6883
9.51k
            window->Collapsed = false;
6884
9.51k
        }
6885
45.5k
        window->WantCollapseToggle = false;
6886
6887
        // SIZE
6888
6889
        // Outer Decoration Sizes
6890
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
6891
45.5k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
6892
45.5k
        window->DecoOuterSizeX1 = 0.0f;
6893
45.5k
        window->DecoOuterSizeX2 = 0.0f;
6894
45.5k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
6895
45.5k
        window->DecoOuterSizeY2 = 0.0f;
6896
45.5k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
6897
6898
        // Calculate auto-fit size, handle automatic resize
6899
45.5k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6900
45.5k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6901
0
        {
6902
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6903
0
            if (!window_size_x_set_by_api)
6904
0
            {
6905
0
                window->SizeFull.x = size_auto_fit.x;
6906
0
                use_current_size_for_scrollbar_x = true;
6907
0
            }
6908
0
            if (!window_size_y_set_by_api)
6909
0
            {
6910
0
                window->SizeFull.y = size_auto_fit.y;
6911
0
                use_current_size_for_scrollbar_y = true;
6912
0
            }
6913
0
        }
6914
45.5k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6915
2
        {
6916
            // Auto-fit may only grow window during the first few frames
6917
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6918
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6919
2
            {
6920
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6921
2
                use_current_size_for_scrollbar_x = true;
6922
2
            }
6923
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6924
2
            {
6925
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6926
2
                use_current_size_for_scrollbar_y = true;
6927
2
            }
6928
2
            if (!window->Collapsed)
6929
2
                MarkIniSettingsDirty(window);
6930
2
        }
6931
6932
        // Apply minimum/maximum window size constraints and final size
6933
45.5k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
6934
45.5k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6935
6936
        // POSITION
6937
6938
        // Popup latch its initial position, will position itself when it appears next frame
6939
45.5k
        if (window_just_activated_by_user)
6940
15
        {
6941
15
            window->AutoPosLastDirection = ImGuiDir_None;
6942
15
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6943
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6944
15
        }
6945
6946
        // Position child window
6947
45.5k
        if (flags & ImGuiWindowFlags_ChildWindow)
6948
9.51k
        {
6949
9.51k
            IM_ASSERT(parent_window && parent_window->Active);
6950
9.51k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
6951
9.51k
            parent_window->DC.ChildWindows.push_back(window);
6952
9.51k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
6953
9.51k
                window->Pos = parent_window->DC.CursorPos;
6954
9.51k
        }
6955
6956
45.5k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
6957
45.5k
        if (window_pos_with_pivot)
6958
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
6959
45.5k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
6960
0
            window->Pos = FindBestWindowPosForPopup(window);
6961
45.5k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
6962
0
            window->Pos = FindBestWindowPosForPopup(window);
6963
45.5k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
6964
0
            window->Pos = FindBestWindowPosForPopup(window);
6965
6966
        // Late create viewport if we don't fit within our current host viewport.
6967
45.5k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_IsMinimized))
6968
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
6969
0
            {
6970
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
6971
                //ImGuiViewport* old_viewport = window->Viewport;
6972
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
6973
6974
                // FIXME-DPI
6975
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
6976
0
                SetCurrentViewport(window, window->Viewport);
6977
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6978
0
                SetCurrentWindow(window);
6979
0
            }
6980
6981
45.5k
        if (window->ViewportOwned)
6982
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
6983
6984
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
6985
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
6986
45.5k
        ImRect viewport_rect(window->Viewport->GetMainRect());
6987
45.5k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
6988
45.5k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
6989
45.5k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
6990
6991
        // Clamp position/size so window stays visible within its viewport or monitor
6992
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
6993
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
6994
45.5k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
6995
36.0k
        {
6996
36.0k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
6997
36.0k
            {
6998
36.0k
                ClampWindowPos(window, visibility_rect);
6999
36.0k
            }
7000
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
7001
0
            {
7002
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
7003
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
7004
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
7005
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
7006
0
                ClampWindowPos(window, visibility_rect);
7007
0
            }
7008
36.0k
        }
7009
45.5k
        window->Pos = ImFloor(window->Pos);
7010
7011
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
7012
        // Large values tend to lead to variety of artifacts and are not recommended.
7013
45.5k
        if (window->ViewportOwned || window->DockIsActive)
7014
0
            window->WindowRounding = 0.0f;
7015
45.5k
        else
7016
45.5k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
7017
7018
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
7019
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
7020
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
7021
7022
        // Apply window focus (new and reactivated windows are moved to front)
7023
45.5k
        bool want_focus = false;
7024
45.5k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
7025
15
        {
7026
15
            if (flags & ImGuiWindowFlags_Popup)
7027
0
                want_focus = true;
7028
15
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
7029
2
                want_focus = true;
7030
15
        }
7031
7032
        // [Test Engine] Register whole window in the item system (before submitting further decorations)
7033
#ifdef IMGUI_ENABLE_TEST_ENGINE
7034
        if (g.TestEngineHookItems)
7035
        {
7036
            IM_ASSERT(window->IDStack.Size == 1);
7037
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
7038
            IMGUI_TEST_ENGINE_ITEM_ADD(window->ID, window->Rect(), NULL);
7039
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
7040
            window->IDStack.Size = 1;
7041
        }
7042
#endif
7043
7044
        // Decide if we are going to handle borders and resize grips
7045
45.5k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
7046
7047
        // Handle manual resize: Resize Grips, Borders, Gamepad
7048
45.5k
        int border_held = -1;
7049
45.5k
        ImU32 resize_grip_col[4] = {};
7050
45.5k
        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
7051
45.5k
        const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
7052
45.5k
        if (handle_borders_and_resize_grips && !window->Collapsed)
7053
37.0k
            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
7054
0
                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
7055
45.5k
        window->ResizeBorderHeld = (signed char)border_held;
7056
7057
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
7058
45.5k
        if (window->ViewportOwned)
7059
0
        {
7060
0
            if (!window->Viewport->PlatformRequestMove)
7061
0
                window->Viewport->Pos = window->Pos;
7062
0
            if (!window->Viewport->PlatformRequestResize)
7063
0
                window->Viewport->Size = window->Size;
7064
0
            window->Viewport->UpdateWorkRect();
7065
0
            viewport_rect = window->Viewport->GetMainRect();
7066
0
        }
7067
7068
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
7069
45.5k
        window->ViewportPos = window->Viewport->Pos;
7070
7071
        // SCROLLBAR VISIBILITY
7072
7073
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
7074
45.5k
        if (!window->Collapsed)
7075
37.0k
        {
7076
            // When reading the current size we need to read it after size constraints have been applied.
7077
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
7078
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
7079
37.0k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
7080
37.0k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
7081
37.0k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
7082
37.0k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
7083
37.0k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
7084
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
7085
37.0k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
7086
37.0k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
7087
37.0k
            if (window->ScrollbarX && !window->ScrollbarY)
7088
851
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
7089
37.0k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
7090
7091
            // Amend the partially filled window->DecorationXXX values.
7092
37.0k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
7093
37.0k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
7094
37.0k
        }
7095
7096
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
7097
        // Update various regions. Variables they depend on should be set above in this function.
7098
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
7099
7100
        // Outer rectangle
7101
        // Not affected by window border size. Used by:
7102
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
7103
        // - Begin() initial clipping rect for drawing window background and borders.
7104
        // - Begin() clipping whole child
7105
45.5k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
7106
45.5k
        const ImRect outer_rect = window->Rect();
7107
45.5k
        const ImRect title_bar_rect = window->TitleBarRect();
7108
45.5k
        window->OuterRectClipped = outer_rect;
7109
45.5k
        if (window->DockIsActive)
7110
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
7111
45.5k
        window->OuterRectClipped.ClipWith(host_rect);
7112
7113
        // Inner rectangle
7114
        // Not affected by window border size. Used by:
7115
        // - InnerClipRect
7116
        // - ScrollToRectEx()
7117
        // - NavUpdatePageUpPageDown()
7118
        // - Scrollbar()
7119
45.5k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
7120
45.5k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
7121
45.5k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
7122
45.5k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
7123
7124
        // Inner clipping rectangle.
7125
        // Will extend a little bit outside the normal work region.
7126
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
7127
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
7128
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
7129
        // Affected by window/frame border size. Used by:
7130
        // - Begin() initial clip rect
7131
45.5k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
7132
45.5k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7133
45.5k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
7134
45.5k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
7135
45.5k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
7136
45.5k
        window->InnerClipRect.ClipWithFull(host_rect);
7137
7138
        // Default item width. Make it proportional to window size if window manually resizes
7139
45.5k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
7140
45.5k
            window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
7141
0
        else
7142
0
            window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
7143
7144
        // SCROLLING
7145
7146
        // Lock down maximum scrolling
7147
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
7148
        // for right/bottom aligned items without creating a scrollbar.
7149
45.5k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
7150
45.5k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
7151
7152
        // Apply scrolling
7153
45.5k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
7154
45.5k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
7155
45.5k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
7156
7157
        // DRAWING
7158
7159
        // Setup draw list and outer clipping rectangle
7160
45.5k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
7161
45.5k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
7162
45.5k
        PushClipRect(host_rect.Min, host_rect.Max, false);
7163
7164
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
7165
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
7166
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
7167
45.5k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
7168
45.5k
        if (is_undocked_or_docked_visible)
7169
45.5k
        {
7170
45.5k
            bool render_decorations_in_parent = false;
7171
45.5k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
7172
9.51k
            {
7173
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
7174
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
7175
9.51k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
7176
9.51k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
7177
9.51k
                bool parent_is_empty = (parent_window->DrawList->VtxBuffer.Size == 0);
7178
9.51k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && !parent_is_empty && !previous_child_overlapping)
7179
9.51k
                    render_decorations_in_parent = true;
7180
9.51k
            }
7181
45.5k
            if (render_decorations_in_parent)
7182
9.51k
                window->DrawList = parent_window->DrawList;
7183
7184
            // Handle title bar, scrollbar, resize grips and resize borders
7185
45.5k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
7186
45.5k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
7187
45.5k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
7188
7189
45.5k
            if (render_decorations_in_parent)
7190
9.51k
                window->DrawList = &window->DrawListInst;
7191
45.5k
        }
7192
7193
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7194
7195
        // Work rectangle.
7196
        // Affected by window padding and border size. Used by:
7197
        // - Columns() for right-most edge
7198
        // - TreeNode(), CollapsingHeader() for right-most edge
7199
        // - BeginTabBar() for right-most edge
7200
45.5k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7201
45.5k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7202
45.5k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7203
45.5k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7204
45.5k
        window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7205
45.5k
        window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7206
45.5k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7207
45.5k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7208
45.5k
        window->ParentWorkRect = window->WorkRect;
7209
7210
        // [LEGACY] Content Region
7211
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7212
        // Used by:
7213
        // - Mouse wheel scrolling + many other things
7214
45.5k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7215
45.5k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7216
45.5k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7217
45.5k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7218
7219
        // Setup drawing context
7220
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7221
45.5k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7222
45.5k
        window->DC.GroupOffset.x = 0.0f;
7223
45.5k
        window->DC.ColumnsOffset.x = 0.0f;
7224
7225
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7226
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7227
45.5k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7228
45.5k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7229
45.5k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7230
45.5k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7231
45.5k
        window->DC.CursorPos = window->DC.CursorStartPos;
7232
45.5k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7233
45.5k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7234
45.5k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7235
45.5k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7236
45.5k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7237
45.5k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7238
7239
45.5k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7240
45.5k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7241
45.5k
        window->DC.NavLayersActiveMaskNext = 0x00;
7242
45.5k
        window->DC.NavIsScrollPushableX = true;
7243
45.5k
        window->DC.NavHideHighlightOneFrame = false;
7244
45.5k
        window->DC.NavWindowHasScrollY = (window->ScrollMax.y > 0.0f);
7245
7246
45.5k
        window->DC.MenuBarAppending = false;
7247
45.5k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7248
45.5k
        window->DC.TreeDepth = 0;
7249
45.5k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7250
45.5k
        window->DC.ChildWindows.resize(0);
7251
45.5k
        window->DC.StateStorage = &window->StateStorage;
7252
45.5k
        window->DC.CurrentColumns = NULL;
7253
45.5k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7254
45.5k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7255
7256
45.5k
        window->DC.ItemWidth = window->ItemWidthDefault;
7257
45.5k
        window->DC.TextWrapPos = -1.0f; // disabled
7258
45.5k
        window->DC.ItemWidthStack.resize(0);
7259
45.5k
        window->DC.TextWrapPosStack.resize(0);
7260
7261
45.5k
        if (window->AutoFitFramesX > 0)
7262
2
            window->AutoFitFramesX--;
7263
45.5k
        if (window->AutoFitFramesY > 0)
7264
2
            window->AutoFitFramesY--;
7265
7266
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7267
        // We ImGuiFocusRequestFlags_UnlessBelowModal to:
7268
        // - Avoid focusing a window that is created outside of a modal. This will prevent active modal from being closed.
7269
        // - Position window behind the modal that is not a begin-parent of this window.
7270
45.5k
        if (want_focus)
7271
2
            FocusWindow(window, ImGuiFocusRequestFlags_UnlessBelowModal);
7272
45.5k
        if (want_focus && window == g.NavWindow)
7273
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7274
7275
        // Close requested by platform window (apply to all windows in this viewport)
7276
45.5k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7277
0
        {
7278
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' closed by PlatformRequestClose\n", window->Name);
7279
0
            *p_open = false;
7280
0
            g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue. // FIXME-NAV: Try removing.
7281
0
        }
7282
7283
        // Title bar
7284
45.5k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7285
36.0k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7286
7287
        // Clear hit test shape every frame
7288
45.5k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7289
7290
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7291
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7292
        // Maybe we can support CTRL+C on every element?
7293
        /*
7294
        //if (g.NavWindow == window && g.ActiveId == 0)
7295
        if (g.ActiveId == window->MoveId)
7296
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7297
                LogToClipboard();
7298
        */
7299
7300
45.5k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7301
45.5k
        {
7302
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7303
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7304
45.5k
            if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
7305
28
                if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7306
28
                    BeginDockableDragDropSource(window);
7307
7308
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7309
45.5k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7310
19
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7311
14
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7312
14
                        BeginDockableDragDropTarget(window);
7313
45.5k
        }
7314
7315
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7316
        // This is useful to allow creating context menus on title bar only, etc.
7317
45.5k
        if (window->DockIsActive)
7318
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7319
45.5k
        else
7320
45.5k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7321
7322
        // [DEBUG]
7323
45.5k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7324
45.5k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7325
0
            DebugLocateItemResolveWithLastItem();
7326
45.5k
#endif
7327
7328
        // [Test Engine] Register title bar / tab with MoveId.
7329
#ifdef IMGUI_ENABLE_TEST_ENGINE
7330
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7331
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.ID, g.LastItemData.Rect, &g.LastItemData);
7332
#endif
7333
45.5k
    }
7334
0
    else
7335
0
    {
7336
        // Append
7337
0
        SetCurrentViewport(window, window->Viewport);
7338
0
        SetCurrentWindow(window);
7339
0
    }
7340
7341
45.5k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7342
45.5k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7343
7344
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7345
45.5k
    window->WriteAccessed = false;
7346
45.5k
    window->BeginCount++;
7347
45.5k
    g.NextWindowData.ClearFlags();
7348
7349
    // Update visibility
7350
45.5k
    if (first_begin_of_the_frame)
7351
45.5k
    {
7352
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7353
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7354
        // This is analogous to regular windows being hidden from one frame.
7355
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7356
45.5k
        if (window->DockIsActive && !window->DockTabIsVisible)
7357
0
        {
7358
0
            if (window->LastFrameJustFocused == g.FrameCount)
7359
0
                window->HiddenFramesCannotSkipItems = 1;
7360
0
            else
7361
0
                window->HiddenFramesCanSkipItems = 1;
7362
0
        }
7363
7364
45.5k
        if (flags & ImGuiWindowFlags_ChildWindow)
7365
9.51k
        {
7366
            // Child window can be out of sight and have "negative" clip windows.
7367
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7368
9.51k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
7369
9.51k
            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
7370
9.51k
            {
7371
9.51k
                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7372
9.51k
                if (!g.LogEnabled && !nav_request)
7373
9.51k
                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7374
952
                        window->HiddenFramesCanSkipItems = 1;
7375
9.51k
            }
7376
7377
            // Hide along with parent or if parent is collapsed
7378
9.51k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7379
0
                window->HiddenFramesCanSkipItems = 1;
7380
9.51k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7381
1
                window->HiddenFramesCannotSkipItems = 1;
7382
9.51k
        }
7383
7384
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7385
45.5k
        if (style.Alpha <= 0.0f)
7386
0
            window->HiddenFramesCanSkipItems = 1;
7387
7388
        // Update the Hidden flag
7389
45.5k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7390
45.5k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7391
7392
        // Disable inputs for requested number of frames
7393
45.5k
        if (window->DisableInputsFrames > 0)
7394
0
        {
7395
0
            window->DisableInputsFrames--;
7396
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7397
0
        }
7398
7399
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7400
45.5k
        bool skip_items = false;
7401
45.5k
        if (window->Collapsed || !window->Active || hidden_regular)
7402
9.45k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7403
9.44k
                skip_items = true;
7404
45.5k
        window->SkipItems = skip_items;
7405
7406
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7407
45.5k
        if (window->SkipItems)
7408
9.44k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7409
7410
        // Sanity check: there are two spots which can set Appearing = true
7411
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7412
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7413
45.5k
        if (window->SkipItems && !window->Appearing)
7414
45.5k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7415
45.5k
    }
7416
7417
    // [DEBUG] io.ConfigDebugBeginReturnValue override return value to test Begin/End and BeginChild/EndChild behaviors.
7418
    // (The implicit fallback window is NOT automatically ended allowing it to always be able to receive commands without crashing)
7419
45.5k
    if (!window->IsFallbackWindow && ((g.IO.ConfigDebugBeginReturnValueOnce && window_just_created) || (g.IO.ConfigDebugBeginReturnValueLoop && g.DebugBeginReturnValueCullDepth == g.CurrentWindowStack.Size)))
7420
0
    {
7421
0
        if (window->AutoFitFramesX > 0) { window->AutoFitFramesX++; }
7422
0
        if (window->AutoFitFramesY > 0) { window->AutoFitFramesY++; }
7423
0
        return false;
7424
0
    }
7425
7426
45.5k
    return !window->SkipItems;
7427
45.5k
}
7428
7429
void ImGui::End()
7430
45.5k
{
7431
45.5k
    ImGuiContext& g = *GImGui;
7432
45.5k
    ImGuiWindow* window = g.CurrentWindow;
7433
7434
    // Error checking: verify that user hasn't called End() too many times!
7435
45.5k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7436
0
    {
7437
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7438
0
        return;
7439
0
    }
7440
45.5k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7441
7442
    // Error checking: verify that user doesn't directly call End() on a child window.
7443
45.5k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7444
45.5k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7445
7446
    // Close anything that is open
7447
45.5k
    if (window->DC.CurrentColumns)
7448
0
        EndColumns();
7449
45.5k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7450
45.5k
        PopClipRect();
7451
45.5k
    PopFocusScope();
7452
7453
    // Stop logging
7454
45.5k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7455
36.0k
        LogFinish();
7456
7457
45.5k
    if (window->DC.IsSetPos)
7458
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7459
7460
    // Docking: report contents sizes to parent to allow for auto-resize
7461
45.5k
    if (window->DockNode && window->DockTabIsVisible)
7462
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7463
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7464
7465
    // Pop from window stack
7466
45.5k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7467
45.5k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7468
0
        g.BeginMenuCount--;
7469
45.5k
    if (window->Flags & ImGuiWindowFlags_Popup)
7470
0
        g.BeginPopupStack.pop_back();
7471
45.5k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithContextState(&g);
7472
45.5k
    g.CurrentWindowStack.pop_back();
7473
45.5k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7474
45.5k
    if (g.CurrentWindow)
7475
27.5k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7476
45.5k
}
7477
7478
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7479
6.14k
{
7480
6.14k
    ImGuiContext& g = *GImGui;
7481
6.14k
    IM_ASSERT(window == window->RootWindow);
7482
7483
6.14k
    const int cur_order = window->FocusOrder;
7484
6.14k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7485
6.14k
    if (g.WindowsFocusOrder.back() == window)
7486
6.14k
        return;
7487
7488
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7489
0
    for (int n = cur_order; n < new_order; n++)
7490
0
    {
7491
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7492
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7493
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7494
0
    }
7495
0
    g.WindowsFocusOrder[new_order] = window;
7496
0
    window->FocusOrder = (short)new_order;
7497
0
}
7498
7499
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7500
6.14k
{
7501
6.14k
    ImGuiContext& g = *GImGui;
7502
6.14k
    ImGuiWindow* current_front_window = g.Windows.back();
7503
6.14k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7504
6.14k
        return;
7505
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7506
0
        if (g.Windows[i] == window)
7507
0
        {
7508
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7509
0
            g.Windows[g.Windows.Size - 1] = window;
7510
0
            break;
7511
0
        }
7512
0
}
7513
7514
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7515
0
{
7516
0
    ImGuiContext& g = *GImGui;
7517
0
    if (g.Windows[0] == window)
7518
0
        return;
7519
0
    for (int i = 0; i < g.Windows.Size; i++)
7520
0
        if (g.Windows[i] == window)
7521
0
        {
7522
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7523
0
            g.Windows[0] = window;
7524
0
            break;
7525
0
        }
7526
0
}
7527
7528
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7529
0
{
7530
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7531
0
    ImGuiContext& g = *GImGui;
7532
0
    window = window->RootWindow;
7533
0
    behind_window = behind_window->RootWindow;
7534
0
    int pos_wnd = FindWindowDisplayIndex(window);
7535
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7536
0
    if (pos_wnd < pos_beh)
7537
0
    {
7538
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7539
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7540
0
        g.Windows[pos_beh - 1] = window;
7541
0
    }
7542
0
    else
7543
0
    {
7544
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7545
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7546
0
        g.Windows[pos_beh] = window;
7547
0
    }
7548
0
}
7549
7550
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7551
0
{
7552
0
    ImGuiContext& g = *GImGui;
7553
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7554
0
}
7555
7556
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7557
void ImGui::FocusWindow(ImGuiWindow* window, ImGuiFocusRequestFlags flags)
7558
11.6k
{
7559
11.6k
    ImGuiContext& g = *GImGui;
7560
7561
    // Modal check?
7562
11.6k
    if ((flags & ImGuiFocusRequestFlags_UnlessBelowModal) && (g.NavWindow != window)) // Early out in common case.
7563
26
        if (ImGuiWindow* blocking_modal = FindBlockingModal(window))
7564
0
        {
7565
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] FocusWindow(\"%s\", UnlessBelowModal): prevented by \"%s\".\n", window ? window->Name : "<NULL>", blocking_modal->Name);
7566
0
            if (window && window == window->RootWindow && (window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7567
0
                BringWindowToDisplayBehind(window, blocking_modal); // Still bring to right below modal.
7568
0
            return;
7569
0
        }
7570
7571
    // Find last focused child (if any) and focus it instead.
7572
11.6k
    if ((flags & ImGuiFocusRequestFlags_RestoreFocusedChild) && window != NULL)
7573
1
        window = NavRestoreLastChildNavWindow(window);
7574
7575
    // Apply focus
7576
11.6k
    if (g.NavWindow != window)
7577
4.83k
    {
7578
4.83k
        SetNavWindow(window);
7579
4.83k
        if (window && g.NavDisableMouseHover)
7580
489
            g.NavMousePosDirty = true;
7581
4.83k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7582
4.83k
        g.NavLayer = ImGuiNavLayer_Main;
7583
4.83k
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7584
4.83k
        g.NavIdIsAlive = false;
7585
7586
        // Close popups if any
7587
4.83k
        ClosePopupsOverWindow(window, false);
7588
4.83k
    }
7589
7590
    // Move the root window to the top of the pile
7591
11.6k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7592
11.6k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7593
11.6k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7594
11.6k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7595
11.6k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7596
7597
    // Steal active widgets. Some of the cases it triggers includes:
7598
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7599
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7600
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7601
11.6k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7602
34
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7603
18
            ClearActiveID();
7604
7605
    // Passing NULL allow to disable keyboard focus
7606
11.6k
    if (!window)
7607
5.54k
        return;
7608
6.14k
    window->LastFrameJustFocused = g.FrameCount;
7609
7610
    // Select in dock node
7611
6.14k
    if (dock_node && dock_node->TabBar)
7612
0
        dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7613
7614
    // Bring to front
7615
6.14k
    BringWindowToFocusFront(focus_front_window);
7616
6.14k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7617
6.14k
        BringWindowToDisplayFront(display_front_window);
7618
6.14k
}
7619
7620
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window, ImGuiViewport* filter_viewport, ImGuiFocusRequestFlags flags)
7621
1
{
7622
1
    ImGuiContext& g = *GImGui;
7623
1
    int start_idx = g.WindowsFocusOrder.Size - 1;
7624
1
    if (under_this_window != NULL)
7625
0
    {
7626
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7627
0
        int offset = -1;
7628
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7629
0
        {
7630
0
            under_this_window = under_this_window->ParentWindow;
7631
0
            offset = 0;
7632
0
        }
7633
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7634
0
    }
7635
1
    for (int i = start_idx; i >= 0; i--)
7636
1
    {
7637
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7638
1
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7639
1
        IM_ASSERT(window == window->RootWindow);
7640
1
        if (window == ignore_window || !window->WasActive)
7641
0
            continue;
7642
1
        if (filter_viewport != NULL && window->Viewport != filter_viewport)
7643
0
            continue;
7644
1
        if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7645
1
        {
7646
            // FIXME-DOCK: When ImGuiFocusRequestFlags_RestoreFocusedChild is set...
7647
            // This is failing (lagging by one frame) for docked windows.
7648
            // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7649
            // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7650
            // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7651
1
            FocusWindow(window, flags);
7652
1
            return;
7653
1
        }
7654
1
    }
7655
0
    FocusWindow(NULL, flags);
7656
0
}
7657
7658
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7659
void ImGui::SetCurrentFont(ImFont* font)
7660
18.0k
{
7661
18.0k
    ImGuiContext& g = *GImGui;
7662
18.0k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7663
18.0k
    IM_ASSERT(font->Scale > 0.0f);
7664
18.0k
    g.Font = font;
7665
18.0k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7666
18.0k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7667
7668
18.0k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7669
18.0k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7670
18.0k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7671
18.0k
    g.DrawListSharedData.Font = g.Font;
7672
18.0k
    g.DrawListSharedData.FontSize = g.FontSize;
7673
18.0k
}
7674
7675
void ImGui::PushFont(ImFont* font)
7676
0
{
7677
0
    ImGuiContext& g = *GImGui;
7678
0
    if (!font)
7679
0
        font = GetDefaultFont();
7680
0
    SetCurrentFont(font);
7681
0
    g.FontStack.push_back(font);
7682
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7683
0
}
7684
7685
void  ImGui::PopFont()
7686
0
{
7687
0
    ImGuiContext& g = *GImGui;
7688
0
    g.CurrentWindow->DrawList->PopTextureID();
7689
0
    g.FontStack.pop_back();
7690
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7691
0
}
7692
7693
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7694
9.51k
{
7695
9.51k
    ImGuiContext& g = *GImGui;
7696
9.51k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7697
9.51k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7698
9.51k
    if (enabled)
7699
0
        item_flags |= option;
7700
9.51k
    else
7701
9.51k
        item_flags &= ~option;
7702
9.51k
    g.CurrentItemFlags = item_flags;
7703
9.51k
    g.ItemFlagsStack.push_back(item_flags);
7704
9.51k
}
7705
7706
void ImGui::PopItemFlag()
7707
9.51k
{
7708
9.51k
    ImGuiContext& g = *GImGui;
7709
9.51k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7710
9.51k
    g.ItemFlagsStack.pop_back();
7711
9.51k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7712
9.51k
}
7713
7714
// BeginDisabled()/EndDisabled()
7715
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7716
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7717
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7718
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7719
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7720
void ImGui::BeginDisabled(bool disabled)
7721
0
{
7722
0
    ImGuiContext& g = *GImGui;
7723
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7724
0
    if (!was_disabled && disabled)
7725
0
    {
7726
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7727
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7728
0
    }
7729
0
    if (was_disabled || disabled)
7730
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7731
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7732
0
    g.DisabledStackSize++;
7733
0
}
7734
7735
void ImGui::EndDisabled()
7736
0
{
7737
0
    ImGuiContext& g = *GImGui;
7738
0
    IM_ASSERT(g.DisabledStackSize > 0);
7739
0
    g.DisabledStackSize--;
7740
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7741
    //PopItemFlag();
7742
0
    g.ItemFlagsStack.pop_back();
7743
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7744
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7745
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7746
0
}
7747
7748
void ImGui::PushTabStop(bool tab_stop)
7749
9.51k
{
7750
9.51k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !tab_stop);
7751
9.51k
}
7752
7753
void ImGui::PopTabStop()
7754
9.51k
{
7755
9.51k
    PopItemFlag();
7756
9.51k
}
7757
7758
void ImGui::PushButtonRepeat(bool repeat)
7759
0
{
7760
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7761
0
}
7762
7763
void ImGui::PopButtonRepeat()
7764
0
{
7765
0
    PopItemFlag();
7766
0
}
7767
7768
void ImGui::PushTextWrapPos(float wrap_pos_x)
7769
0
{
7770
0
    ImGuiWindow* window = GetCurrentWindow();
7771
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7772
0
    window->DC.TextWrapPos = wrap_pos_x;
7773
0
}
7774
7775
void ImGui::PopTextWrapPos()
7776
0
{
7777
0
    ImGuiWindow* window = GetCurrentWindow();
7778
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7779
0
    window->DC.TextWrapPosStack.pop_back();
7780
0
}
7781
7782
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7783
0
{
7784
0
    ImGuiWindow* last_window = NULL;
7785
0
    while (last_window != window)
7786
0
    {
7787
0
        last_window = window;
7788
0
        window = window->RootWindow;
7789
0
        if (popup_hierarchy)
7790
0
            window = window->RootWindowPopupTree;
7791
0
    if (dock_hierarchy)
7792
0
      window = window->RootWindowDockTree;
7793
0
  }
7794
0
    return window;
7795
0
}
7796
7797
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7798
0
{
7799
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7800
0
    if (window_root == potential_parent)
7801
0
        return true;
7802
0
    while (window != NULL)
7803
0
    {
7804
0
        if (window == potential_parent)
7805
0
            return true;
7806
0
        if (window == window_root) // end of chain
7807
0
            return false;
7808
0
        window = window->ParentWindow;
7809
0
    }
7810
0
    return false;
7811
0
}
7812
7813
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7814
0
{
7815
0
    if (window->RootWindow == potential_parent)
7816
0
        return true;
7817
0
    while (window != NULL)
7818
0
    {
7819
0
        if (window == potential_parent)
7820
0
            return true;
7821
0
        window = window->ParentWindowInBeginStack;
7822
0
    }
7823
0
    return false;
7824
0
}
7825
7826
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7827
0
{
7828
0
    ImGuiContext& g = *GImGui;
7829
7830
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7831
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7832
0
    if (display_layer_delta != 0)
7833
0
        return display_layer_delta > 0;
7834
7835
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7836
0
    {
7837
0
        ImGuiWindow* candidate_window = g.Windows[i];
7838
0
        if (candidate_window == potential_above)
7839
0
            return true;
7840
0
        if (candidate_window == potential_below)
7841
0
            return false;
7842
0
    }
7843
0
    return false;
7844
0
}
7845
7846
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7847
14.5k
{
7848
14.5k
    IM_ASSERT((flags & ~ImGuiHoveredFlags_AllowedMaskForIsWindowHovered) == 0 && "Invalid flags for IsWindowHovered()!");
7849
7850
14.5k
    ImGuiContext& g = *GImGui;
7851
14.5k
    ImGuiWindow* ref_window = g.HoveredWindow;
7852
14.5k
    ImGuiWindow* cur_window = g.CurrentWindow;
7853
14.5k
    if (ref_window == NULL)
7854
14.0k
        return false;
7855
7856
438
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7857
438
    {
7858
438
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
7859
438
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7860
438
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
7861
438
        if (flags & ImGuiHoveredFlags_RootWindow)
7862
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7863
7864
438
        bool result;
7865
438
        if (flags & ImGuiHoveredFlags_ChildWindows)
7866
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7867
438
        else
7868
438
            result = (ref_window == cur_window);
7869
438
        if (!result)
7870
437
            return false;
7871
438
    }
7872
7873
1
    if (!IsWindowContentHoverable(ref_window, flags))
7874
0
        return false;
7875
1
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7876
1
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7877
0
            return false;
7878
7879
    // When changing hovered window we requires a bit of stationary delay before activating hover timer.
7880
    // FIXME: We don't support delay other than stationary one for now, other delay would need a way
7881
    // to fullfill the possibility that multiple IsWindowHovered() with varying flag could return true
7882
    // for different windows of the hierarchy. Possibly need a Hash(Current+Flags) ==> (Timer) cache.
7883
    // We can implement this for _Stationary because the data is linked to HoveredWindow rather than CurrentWindow.
7884
1
    if (flags & ImGuiHoveredFlags_ForTooltip)
7885
0
        flags |= g.Style.HoverFlagsForTooltipMouse;
7886
1
    if ((flags & ImGuiHoveredFlags_Stationary) != 0 && g.HoverWindowUnlockedStationaryId != ref_window->ID)
7887
0
        return false;
7888
7889
1
    return true;
7890
1
}
7891
7892
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7893
18.9k
{
7894
18.9k
    ImGuiContext& g = *GImGui;
7895
18.9k
    ImGuiWindow* ref_window = g.NavWindow;
7896
18.9k
    ImGuiWindow* cur_window = g.CurrentWindow;
7897
7898
18.9k
    if (ref_window == NULL)
7899
8.49k
        return false;
7900
10.4k
    if (flags & ImGuiFocusedFlags_AnyWindow)
7901
0
        return true;
7902
7903
10.4k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
7904
10.4k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7905
10.4k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
7906
10.4k
    if (flags & ImGuiHoveredFlags_RootWindow)
7907
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7908
7909
10.4k
    if (flags & ImGuiHoveredFlags_ChildWindows)
7910
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7911
10.4k
    else
7912
10.4k
        return (ref_window == cur_window);
7913
10.4k
}
7914
7915
ImGuiID ImGui::GetWindowDockID()
7916
0
{
7917
0
    ImGuiContext& g = *GImGui;
7918
0
    return g.CurrentWindow->DockId;
7919
0
}
7920
7921
bool ImGui::IsWindowDocked()
7922
0
{
7923
0
    ImGuiContext& g = *GImGui;
7924
0
    return g.CurrentWindow->DockIsActive;
7925
0
}
7926
7927
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7928
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7929
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7930
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7931
0
{
7932
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7933
0
}
7934
7935
float ImGui::GetWindowWidth()
7936
5.98k
{
7937
5.98k
    ImGuiWindow* window = GImGui->CurrentWindow;
7938
5.98k
    return window->Size.x;
7939
5.98k
}
7940
7941
float ImGui::GetWindowHeight()
7942
5.99k
{
7943
5.99k
    ImGuiWindow* window = GImGui->CurrentWindow;
7944
5.99k
    return window->Size.y;
7945
5.99k
}
7946
7947
ImVec2 ImGui::GetWindowPos()
7948
0
{
7949
0
    ImGuiContext& g = *GImGui;
7950
0
    ImGuiWindow* window = g.CurrentWindow;
7951
0
    return window->Pos;
7952
0
}
7953
7954
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
7955
2
{
7956
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7957
2
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
7958
0
        return;
7959
7960
2
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7961
2
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7962
2
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
7963
7964
    // Set
7965
2
    const ImVec2 old_pos = window->Pos;
7966
2
    window->Pos = ImFloor(pos);
7967
2
    ImVec2 offset = window->Pos - old_pos;
7968
2
    if (offset.x == 0.0f && offset.y == 0.0f)
7969
0
        return;
7970
2
    MarkIniSettingsDirty(window);
7971
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
7972
2
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
7973
2
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
7974
2
    window->DC.IdealMaxPos += offset;
7975
2
    window->DC.CursorStartPos += offset;
7976
2
}
7977
7978
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
7979
0
{
7980
0
    ImGuiWindow* window = GetCurrentWindowRead();
7981
0
    SetWindowPos(window, pos, cond);
7982
0
}
7983
7984
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
7985
0
{
7986
0
    if (ImGuiWindow* window = FindWindowByName(name))
7987
0
        SetWindowPos(window, pos, cond);
7988
0
}
7989
7990
ImVec2 ImGui::GetWindowSize()
7991
0
{
7992
0
    ImGuiWindow* window = GetCurrentWindowRead();
7993
0
    return window->Size;
7994
0
}
7995
7996
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
7997
27.5k
{
7998
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7999
27.5k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
8000
18.0k
        return;
8001
8002
9.51k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8003
9.51k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8004
8005
    // Set
8006
9.51k
    ImVec2 old_size = window->SizeFull;
8007
9.51k
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
8008
9.51k
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
8009
9.51k
    if (size.x <= 0.0f)
8010
0
        window->AutoFitOnlyGrows = false;
8011
9.51k
    else
8012
9.51k
        window->SizeFull.x = IM_FLOOR(size.x);
8013
9.51k
    if (size.y <= 0.0f)
8014
0
        window->AutoFitOnlyGrows = false;
8015
9.51k
    else
8016
9.51k
        window->SizeFull.y = IM_FLOOR(size.y);
8017
9.51k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
8018
1.89k
        MarkIniSettingsDirty(window);
8019
9.51k
}
8020
8021
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
8022
0
{
8023
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
8024
0
}
8025
8026
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
8027
0
{
8028
0
    if (ImGuiWindow* window = FindWindowByName(name))
8029
0
        SetWindowSize(window, size, cond);
8030
0
}
8031
8032
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
8033
0
{
8034
    // Test condition (NB: bit 0 is always true) and clear flags for next time
8035
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
8036
0
        return;
8037
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
8038
8039
    // Set
8040
0
    window->Collapsed = collapsed;
8041
0
}
8042
8043
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
8044
0
{
8045
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
8046
0
    window->HitTestHoleSize = ImVec2ih(size);
8047
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
8048
0
}
8049
8050
void ImGui::SetWindowHiddendAndSkipItemsForCurrentFrame(ImGuiWindow* window)
8051
0
{
8052
0
    window->Hidden = window->SkipItems = true;
8053
0
    window->HiddenFramesCanSkipItems = 1;
8054
0
}
8055
8056
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
8057
0
{
8058
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
8059
0
}
8060
8061
bool ImGui::IsWindowCollapsed()
8062
0
{
8063
0
    ImGuiWindow* window = GetCurrentWindowRead();
8064
0
    return window->Collapsed;
8065
0
}
8066
8067
bool ImGui::IsWindowAppearing()
8068
0
{
8069
0
    ImGuiWindow* window = GetCurrentWindowRead();
8070
0
    return window->Appearing;
8071
0
}
8072
8073
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
8074
0
{
8075
0
    if (ImGuiWindow* window = FindWindowByName(name))
8076
0
        SetWindowCollapsed(window, collapsed, cond);
8077
0
}
8078
8079
void ImGui::SetWindowFocus()
8080
5.98k
{
8081
5.98k
    FocusWindow(GImGui->CurrentWindow);
8082
5.98k
}
8083
8084
void ImGui::SetWindowFocus(const char* name)
8085
0
{
8086
0
    if (name)
8087
0
    {
8088
0
        if (ImGuiWindow* window = FindWindowByName(name))
8089
0
            FocusWindow(window);
8090
0
    }
8091
0
    else
8092
0
    {
8093
0
        FocusWindow(NULL);
8094
0
    }
8095
0
}
8096
8097
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
8098
0
{
8099
0
    ImGuiContext& g = *GImGui;
8100
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8101
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
8102
0
    g.NextWindowData.PosVal = pos;
8103
0
    g.NextWindowData.PosPivotVal = pivot;
8104
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
8105
0
    g.NextWindowData.PosUndock = true;
8106
0
}
8107
8108
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
8109
27.5k
{
8110
27.5k
    ImGuiContext& g = *GImGui;
8111
27.5k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8112
27.5k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
8113
27.5k
    g.NextWindowData.SizeVal = size;
8114
27.5k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
8115
27.5k
}
8116
8117
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
8118
0
{
8119
0
    ImGuiContext& g = *GImGui;
8120
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
8121
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
8122
0
    g.NextWindowData.SizeCallback = custom_callback;
8123
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
8124
0
}
8125
8126
// Content size = inner scrollable rectangle, padded with WindowPadding.
8127
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
8128
void ImGui::SetNextWindowContentSize(const ImVec2& size)
8129
0
{
8130
0
    ImGuiContext& g = *GImGui;
8131
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
8132
0
    g.NextWindowData.ContentSizeVal = ImFloor(size);
8133
0
}
8134
8135
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
8136
0
{
8137
0
    ImGuiContext& g = *GImGui;
8138
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
8139
0
    g.NextWindowData.ScrollVal = scroll;
8140
0
}
8141
8142
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
8143
0
{
8144
0
    ImGuiContext& g = *GImGui;
8145
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
8146
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
8147
0
    g.NextWindowData.CollapsedVal = collapsed;
8148
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
8149
0
}
8150
8151
void ImGui::SetNextWindowFocus()
8152
0
{
8153
0
    ImGuiContext& g = *GImGui;
8154
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
8155
0
}
8156
8157
void ImGui::SetNextWindowBgAlpha(float alpha)
8158
0
{
8159
0
    ImGuiContext& g = *GImGui;
8160
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
8161
0
    g.NextWindowData.BgAlphaVal = alpha;
8162
0
}
8163
8164
void ImGui::SetNextWindowViewport(ImGuiID id)
8165
0
{
8166
0
    ImGuiContext& g = *GImGui;
8167
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
8168
0
    g.NextWindowData.ViewportId = id;
8169
0
}
8170
8171
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
8172
0
{
8173
0
    ImGuiContext& g = *GImGui;
8174
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
8175
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
8176
0
    g.NextWindowData.DockId = id;
8177
0
}
8178
8179
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
8180
0
{
8181
0
    ImGuiContext& g = *GImGui;
8182
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
8183
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
8184
0
    g.NextWindowData.WindowClass = *window_class;
8185
0
}
8186
8187
ImDrawList* ImGui::GetWindowDrawList()
8188
9.51k
{
8189
9.51k
    ImGuiWindow* window = GetCurrentWindow();
8190
9.51k
    return window->DrawList;
8191
9.51k
}
8192
8193
float ImGui::GetWindowDpiScale()
8194
0
{
8195
0
    ImGuiContext& g = *GImGui;
8196
0
    return g.CurrentDpiScale;
8197
0
}
8198
8199
ImGuiViewport* ImGui::GetWindowViewport()
8200
0
{
8201
0
    ImGuiContext& g = *GImGui;
8202
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
8203
0
    return g.CurrentViewport;
8204
0
}
8205
8206
ImFont* ImGui::GetFont()
8207
810k
{
8208
810k
    return GImGui->Font;
8209
810k
}
8210
8211
float ImGui::GetFontSize()
8212
810k
{
8213
810k
    return GImGui->FontSize;
8214
810k
}
8215
8216
ImVec2 ImGui::GetFontTexUvWhitePixel()
8217
0
{
8218
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
8219
0
}
8220
8221
void ImGui::SetWindowFontScale(float scale)
8222
0
{
8223
0
    IM_ASSERT(scale > 0.0f);
8224
0
    ImGuiContext& g = *GImGui;
8225
0
    ImGuiWindow* window = GetCurrentWindow();
8226
0
    window->FontWindowScale = scale;
8227
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
8228
0
}
8229
8230
void ImGui::PushFocusScope(ImGuiID id)
8231
45.5k
{
8232
45.5k
    ImGuiContext& g = *GImGui;
8233
45.5k
    g.FocusScopeStack.push_back(id);
8234
45.5k
    g.CurrentFocusScopeId = id;
8235
45.5k
}
8236
8237
void ImGui::PopFocusScope()
8238
45.5k
{
8239
45.5k
    ImGuiContext& g = *GImGui;
8240
45.5k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8241
45.5k
    g.FocusScopeStack.pop_back();
8242
45.5k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8243
45.5k
}
8244
8245
// Focus = move navigation cursor, set scrolling, set focus window.
8246
void ImGui::FocusItem()
8247
0
{
8248
0
    ImGuiContext& g = *GImGui;
8249
0
    ImGuiWindow* window = g.CurrentWindow;
8250
0
    IMGUI_DEBUG_LOG_FOCUS("FocusItem(0x%08x) in window \"%s\"\n", g.LastItemData.ID, window->Name);
8251
0
    if (g.DragDropActive || g.MovingWindow != NULL) // FIXME: Opt-in flags for this?
8252
0
    {
8253
0
        IMGUI_DEBUG_LOG_FOCUS("FocusItem() ignored while DragDropActive!\n");
8254
0
        return;
8255
0
    }
8256
8257
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi | ImGuiNavMoveFlags_NoSelect;
8258
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8259
0
    SetNavWindow(window);
8260
0
    NavMoveRequestSubmit(ImGuiDir_None, ImGuiDir_Up, move_flags, scroll_flags);
8261
0
    NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8262
0
}
8263
8264
void ImGui::ActivateItemByID(ImGuiID id)
8265
0
{
8266
0
    ImGuiContext& g = *GImGui;
8267
0
    g.NavNextActivateId = id;
8268
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8269
0
}
8270
8271
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8272
// But ActivateItem() should function without altering scroll/focus?
8273
void ImGui::SetKeyboardFocusHere(int offset)
8274
0
{
8275
0
    ImGuiContext& g = *GImGui;
8276
0
    ImGuiWindow* window = g.CurrentWindow;
8277
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8278
0
    IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8279
8280
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8281
    // When we refactor this function into ActivateItem() we may want to make this an option.
8282
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8283
    // is also automatically dropped in the event g.ActiveId is stolen.
8284
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8285
0
    {
8286
0
        IMGUI_DEBUG_LOG_FOCUS("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8287
0
        return;
8288
0
    }
8289
8290
0
    SetNavWindow(window);
8291
8292
0
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_Activate | ImGuiNavMoveFlags_FocusApi;
8293
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8294
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8295
0
    if (offset == -1)
8296
0
    {
8297
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8298
0
    }
8299
0
    else
8300
0
    {
8301
0
        g.NavTabbingDir = 1;
8302
0
        g.NavTabbingCounter = offset + 1;
8303
0
    }
8304
0
}
8305
8306
void ImGui::SetItemDefaultFocus()
8307
0
{
8308
0
    ImGuiContext& g = *GImGui;
8309
0
    ImGuiWindow* window = g.CurrentWindow;
8310
0
    if (!window->Appearing)
8311
0
        return;
8312
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResult.ID == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8313
0
        return;
8314
8315
0
    g.NavInitRequest = false;
8316
0
    NavApplyItemToResult(&g.NavInitResult);
8317
0
    NavUpdateAnyRequestFlag();
8318
8319
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8320
0
    if (!window->ClipRect.Contains(g.LastItemData.Rect))
8321
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8322
0
}
8323
8324
void ImGui::SetStateStorage(ImGuiStorage* tree)
8325
0
{
8326
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8327
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8328
0
}
8329
8330
ImGuiStorage* ImGui::GetStateStorage()
8331
0
{
8332
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8333
0
    return window->DC.StateStorage;
8334
0
}
8335
8336
void ImGui::PushID(const char* str_id)
8337
9.51k
{
8338
9.51k
    ImGuiContext& g = *GImGui;
8339
9.51k
    ImGuiWindow* window = g.CurrentWindow;
8340
9.51k
    ImGuiID id = window->GetID(str_id);
8341
9.51k
    window->IDStack.push_back(id);
8342
9.51k
}
8343
8344
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8345
0
{
8346
0
    ImGuiContext& g = *GImGui;
8347
0
    ImGuiWindow* window = g.CurrentWindow;
8348
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8349
0
    window->IDStack.push_back(id);
8350
0
}
8351
8352
void ImGui::PushID(const void* ptr_id)
8353
0
{
8354
0
    ImGuiContext& g = *GImGui;
8355
0
    ImGuiWindow* window = g.CurrentWindow;
8356
0
    ImGuiID id = window->GetID(ptr_id);
8357
0
    window->IDStack.push_back(id);
8358
0
}
8359
8360
void ImGui::PushID(int int_id)
8361
0
{
8362
0
    ImGuiContext& g = *GImGui;
8363
0
    ImGuiWindow* window = g.CurrentWindow;
8364
0
    ImGuiID id = window->GetID(int_id);
8365
0
    window->IDStack.push_back(id);
8366
0
}
8367
8368
// Push a given id value ignoring the ID stack as a seed.
8369
void ImGui::PushOverrideID(ImGuiID id)
8370
0
{
8371
0
    ImGuiContext& g = *GImGui;
8372
0
    ImGuiWindow* window = g.CurrentWindow;
8373
0
    if (g.DebugHookIdInfo == id)
8374
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8375
0
    window->IDStack.push_back(id);
8376
0
}
8377
8378
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8379
// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
8380
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8381
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8382
0
{
8383
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8384
0
    ImGuiContext& g = *GImGui;
8385
0
    if (g.DebugHookIdInfo == id)
8386
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8387
0
    return id;
8388
0
}
8389
8390
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8391
0
{
8392
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8393
0
    ImGuiContext& g = *GImGui;
8394
0
    if (g.DebugHookIdInfo == id)
8395
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8396
0
    return id;
8397
0
}
8398
8399
void ImGui::PopID()
8400
9.51k
{
8401
9.51k
    ImGuiWindow* window = GImGui->CurrentWindow;
8402
9.51k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8403
9.51k
    window->IDStack.pop_back();
8404
9.51k
}
8405
8406
ImGuiID ImGui::GetID(const char* str_id)
8407
0
{
8408
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8409
0
    return window->GetID(str_id);
8410
0
}
8411
8412
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8413
0
{
8414
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8415
0
    return window->GetID(str_id_begin, str_id_end);
8416
0
}
8417
8418
ImGuiID ImGui::GetID(const void* ptr_id)
8419
0
{
8420
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8421
0
    return window->GetID(ptr_id);
8422
0
}
8423
8424
bool ImGui::IsRectVisible(const ImVec2& size)
8425
0
{
8426
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8427
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8428
0
}
8429
8430
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8431
0
{
8432
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8433
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8434
0
}
8435
8436
8437
//-----------------------------------------------------------------------------
8438
// [SECTION] INPUTS
8439
//-----------------------------------------------------------------------------
8440
// - GetKeyData() [Internal]
8441
// - GetKeyIndex() [Internal]
8442
// - GetKeyName()
8443
// - GetKeyChordName() [Internal]
8444
// - CalcTypematicRepeatAmount() [Internal]
8445
// - GetTypematicRepeatRate() [Internal]
8446
// - GetKeyPressedAmount() [Internal]
8447
// - GetKeyMagnitude2d() [Internal]
8448
//-----------------------------------------------------------------------------
8449
// - UpdateKeyRoutingTable() [Internal]
8450
// - GetRoutingIdFromOwnerId() [Internal]
8451
// - GetShortcutRoutingData() [Internal]
8452
// - CalcRoutingScore() [Internal]
8453
// - SetShortcutRouting() [Internal]
8454
// - TestShortcutRouting() [Internal]
8455
//-----------------------------------------------------------------------------
8456
// - IsKeyDown()
8457
// - IsKeyPressed()
8458
// - IsKeyReleased()
8459
//-----------------------------------------------------------------------------
8460
// - IsMouseDown()
8461
// - IsMouseClicked()
8462
// - IsMouseReleased()
8463
// - IsMouseDoubleClicked()
8464
// - GetMouseClickedCount()
8465
// - IsMouseHoveringRect() [Internal]
8466
// - IsMouseDragPastThreshold() [Internal]
8467
// - IsMouseDragging()
8468
// - GetMousePos()
8469
// - GetMousePosOnOpeningCurrentPopup()
8470
// - IsMousePosValid()
8471
// - IsAnyMouseDown()
8472
// - GetMouseDragDelta()
8473
// - ResetMouseDragDelta()
8474
// - GetMouseCursor()
8475
// - SetMouseCursor()
8476
//-----------------------------------------------------------------------------
8477
// - UpdateAliasKey()
8478
// - GetMergedModsFromKeys()
8479
// - UpdateKeyboardInputs()
8480
// - UpdateMouseInputs()
8481
//-----------------------------------------------------------------------------
8482
// - LockWheelingWindow [Internal]
8483
// - FindBestWheelingWindow [Internal]
8484
// - UpdateMouseWheel() [Internal]
8485
//-----------------------------------------------------------------------------
8486
// - SetNextFrameWantCaptureKeyboard()
8487
// - SetNextFrameWantCaptureMouse()
8488
//-----------------------------------------------------------------------------
8489
// - GetInputSourceName() [Internal]
8490
// - DebugPrintInputEvent() [Internal]
8491
// - UpdateInputEvents() [Internal]
8492
//-----------------------------------------------------------------------------
8493
// - GetKeyOwner() [Internal]
8494
// - TestKeyOwner() [Internal]
8495
// - SetKeyOwner() [Internal]
8496
// - SetItemKeyOwner() [Internal]
8497
// - Shortcut() [Internal]
8498
//-----------------------------------------------------------------------------
8499
8500
ImGuiKeyData* ImGui::GetKeyData(ImGuiContext* ctx, ImGuiKey key)
8501
551k
{
8502
551k
    ImGuiContext& g = *ctx;
8503
8504
    // Special storage location for mods
8505
551k
    if (key & ImGuiMod_Mask_)
8506
162k
        key = ConvertSingleModFlagToKey(ctx, key);
8507
8508
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8509
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8510
    if (IsLegacyKey(key) && g.IO.KeyMap[key] != -1)
8511
        key = (ImGuiKey)g.IO.KeyMap[key];  // Remap native->imgui or imgui->native
8512
#else
8513
551k
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8514
551k
#endif
8515
551k
    return &g.IO.KeysData[key - ImGuiKey_KeysData_OFFSET];
8516
551k
}
8517
8518
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8519
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8520
{
8521
    ImGuiContext& g = *GImGui;
8522
    IM_ASSERT(IsNamedKey(key));
8523
    const ImGuiKeyData* key_data = GetKeyData(key);
8524
    return (ImGuiKey)(key_data - g.IO.KeysData);
8525
}
8526
#endif
8527
8528
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8529
static const char* const GKeyNames[] =
8530
{
8531
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8532
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8533
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8534
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8535
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8536
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8537
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8538
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8539
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8540
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8541
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8542
    "GamepadStart", "GamepadBack",
8543
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8544
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8545
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8546
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8547
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8548
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8549
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8550
};
8551
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8552
8553
const char* ImGui::GetKeyName(ImGuiKey key)
8554
0
{
8555
0
    ImGuiContext& g = *GImGui;
8556
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8557
0
    IM_ASSERT((IsNamedKeyOrModKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8558
#else
8559
    if (IsLegacyKey(key))
8560
    {
8561
        if (g.IO.KeyMap[key] == -1)
8562
            return "N/A";
8563
        IM_ASSERT(IsNamedKey((ImGuiKey)g.IO.KeyMap[key]));
8564
        key = (ImGuiKey)g.IO.KeyMap[key];
8565
    }
8566
#endif
8567
0
    if (key == ImGuiKey_None)
8568
0
        return "None";
8569
0
    if (key & ImGuiMod_Mask_)
8570
0
        key = ConvertSingleModFlagToKey(&g, key);
8571
0
    if (!IsNamedKey(key))
8572
0
        return "Unknown";
8573
8574
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8575
0
}
8576
8577
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8578
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8579
0
{
8580
0
    ImGuiContext& g = *GImGui;
8581
0
    if (key_chord & ImGuiMod_Shortcut)
8582
0
        key_chord = ConvertShortcutMod(key_chord);
8583
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8584
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8585
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8586
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8587
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8588
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8589
0
}
8590
8591
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8592
// t1 = current time (e.g.: g.Time)
8593
// An event is triggered at:
8594
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8595
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8596
265
{
8597
265
    if (t1 == 0.0f)
8598
0
        return 1;
8599
265
    if (t0 >= t1)
8600
0
        return 0;
8601
265
    if (repeat_rate <= 0.0f)
8602
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8603
265
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8604
265
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8605
265
    const int count = count_t1 - count_t0;
8606
265
    return count;
8607
265
}
8608
8609
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8610
2.06k
{
8611
2.06k
    ImGuiContext& g = *GImGui;
8612
2.06k
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8613
2.06k
    {
8614
658
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8615
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8616
1.40k
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8617
2.06k
    }
8618
2.06k
}
8619
8620
// Return value representing the number of presses in the last time period, for the given repeat rate
8621
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8622
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8623
265
{
8624
265
    ImGuiContext& g = *GImGui;
8625
265
    const ImGuiKeyData* key_data = GetKeyData(key);
8626
265
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8627
0
        return 0;
8628
265
    const float t = key_data->DownDuration;
8629
265
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8630
265
}
8631
8632
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8633
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8634
0
{
8635
0
    return ImVec2(
8636
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8637
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8638
0
}
8639
8640
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8641
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8642
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8643
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8644
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8645
18.0k
{
8646
18.0k
    ImGuiContext& g = *GImGui;
8647
18.0k
    rt->EntriesNext.resize(0);
8648
2.53M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8649
2.52M
    {
8650
2.52M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8651
2.52M
        ImGuiKeyRoutingData* routing_entry;
8652
2.52M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8653
0
        {
8654
0
            routing_entry = &rt->Entries[old_routing_idx];
8655
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8656
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8657
0
            routing_entry->RoutingNextScore = 255;
8658
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8659
0
                continue;
8660
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8661
8662
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8663
0
            if (routing_entry->Mods == g.IO.KeyMods)
8664
0
            {
8665
0
                ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
8666
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8667
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8668
0
            }
8669
0
        }
8670
8671
        // Rewrite linked-list
8672
2.52M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8673
2.52M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8674
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8675
2.52M
    }
8676
18.0k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8677
18.0k
}
8678
8679
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8680
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8681
0
{
8682
0
    ImGuiContext& g = *GImGui;
8683
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8684
0
}
8685
8686
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8687
0
{
8688
    // Majority of shortcuts will be Key + any number of Mods
8689
    // We accept _Single_ mod with ImGuiKey_None.
8690
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8691
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8692
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8693
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8694
0
    ImGuiContext& g = *GImGui;
8695
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8696
0
    ImGuiKeyRoutingData* routing_data;
8697
0
    if (key_chord & ImGuiMod_Shortcut)
8698
0
        key_chord = ConvertShortcutMod(key_chord);
8699
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8700
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8701
0
    if (key == ImGuiKey_None)
8702
0
        key = ConvertSingleModFlagToKey(&g, mods);
8703
0
    IM_ASSERT(IsNamedKey(key));
8704
8705
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8706
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8707
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8708
0
    {
8709
0
        routing_data = &rt->Entries[idx];
8710
0
        if (routing_data->Mods == mods)
8711
0
            return routing_data;
8712
0
    }
8713
8714
    // Add to linked-list
8715
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8716
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8717
0
    routing_data = &rt->Entries[routing_data_idx];
8718
0
    routing_data->Mods = (ImU16)mods;
8719
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8720
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8721
0
    return routing_data;
8722
0
}
8723
8724
// Current score encoding (lower is highest priority):
8725
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8726
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8727
//  -   2: ImGuiInputFlags_RouteGlobal
8728
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8729
//  - 254: ImGuiInputFlags_RouteGlobalLow
8730
//  - 255: never route
8731
// 'flags' should include an explicit routing policy
8732
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8733
0
{
8734
0
    if (flags & ImGuiInputFlags_RouteFocused)
8735
0
    {
8736
0
        ImGuiContext& g = *GImGui;
8737
0
        ImGuiWindow* focused = g.NavWindow;
8738
8739
        // ActiveID gets top priority
8740
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8741
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8742
0
            return 1;
8743
8744
        // Score based on distance to focused window (lower is better)
8745
        // Assuming both windows are submitting a routing request,
8746
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8747
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8748
        // Assuming only WindowA is submitting a routing request,
8749
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8750
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8751
0
            for (int next_score = 3; focused != NULL; next_score++)
8752
0
            {
8753
0
                if (focused == location)
8754
0
                {
8755
0
                    IM_ASSERT(next_score < 255);
8756
0
                    return next_score;
8757
0
                }
8758
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8759
0
            }
8760
0
        return 255;
8761
0
    }
8762
8763
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8764
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8765
0
        return 2;
8766
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8767
0
        return 254;
8768
0
    return 0;
8769
0
}
8770
8771
// Request a desired route for an input chord (key + mods).
8772
// Return true if the route is available this frame.
8773
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8774
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8775
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8776
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8777
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8778
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8779
36.0k
{
8780
36.0k
    ImGuiContext& g = *GImGui;
8781
36.0k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8782
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8783
36.0k
    else
8784
36.0k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8785
8786
36.0k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8787
0
        if (g.NavWindow == NULL)
8788
0
            return false;
8789
36.0k
    if (flags & ImGuiInputFlags_RouteAlways)
8790
36.0k
        return true;
8791
8792
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8793
0
    if (score == 255)
8794
0
        return false;
8795
8796
    // Submit routing for NEXT frame (assuming score is sufficient)
8797
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8798
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8799
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8800
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8801
0
    if (score < routing_data->RoutingNextScore)
8802
0
    {
8803
0
        routing_data->RoutingNext = routing_id;
8804
0
        routing_data->RoutingNextScore = (ImU8)score;
8805
0
    }
8806
8807
    // Return routing state for CURRENT frame
8808
0
    return routing_data->RoutingCurr == routing_id;
8809
0
}
8810
8811
// Currently unused by core (but used by tests)
8812
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8813
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8814
0
{
8815
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8816
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8817
0
    return routing_data->RoutingCurr == routing_id;
8818
0
}
8819
8820
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8821
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8822
bool ImGui::IsKeyDown(ImGuiKey key)
8823
270k
{
8824
270k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8825
270k
}
8826
8827
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8828
280k
{
8829
280k
    const ImGuiKeyData* key_data = GetKeyData(key);
8830
280k
    if (!key_data->Down)
8831
275k
        return false;
8832
5.38k
    if (!TestKeyOwner(key, owner_id))
8833
6
        return false;
8834
5.37k
    return true;
8835
5.38k
}
8836
8837
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8838
69.4k
{
8839
69.4k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8840
69.4k
}
8841
8842
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8843
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8844
142k
{
8845
142k
    const ImGuiKeyData* key_data = GetKeyData(key);
8846
142k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8847
138k
        return false;
8848
3.53k
    const float t = key_data->DownDuration;
8849
3.53k
    if (t < 0.0f)
8850
0
        return false;
8851
3.53k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8852
8853
3.53k
    bool pressed = (t == 0.0f);
8854
3.53k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
8855
2.06k
    {
8856
2.06k
        float repeat_delay, repeat_rate;
8857
2.06k
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
8858
2.06k
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8859
2.06k
    }
8860
3.53k
    if (!pressed)
8861
3.08k
        return false;
8862
453
    if (!TestKeyOwner(key, owner_id))
8863
2
        return false;
8864
451
    return true;
8865
453
}
8866
8867
bool ImGui::IsKeyReleased(ImGuiKey key)
8868
0
{
8869
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
8870
0
}
8871
8872
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8873
0
{
8874
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8875
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8876
0
        return false;
8877
0
    if (!TestKeyOwner(key, owner_id))
8878
0
        return false;
8879
0
    return true;
8880
0
}
8881
8882
bool ImGui::IsMouseDown(ImGuiMouseButton button)
8883
0
{
8884
0
    ImGuiContext& g = *GImGui;
8885
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8886
0
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
8887
0
}
8888
8889
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8890
138
{
8891
138
    ImGuiContext& g = *GImGui;
8892
138
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8893
138
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
8894
138
}
8895
8896
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8897
4
{
8898
4
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8899
4
}
8900
8901
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
8902
284
{
8903
284
    ImGuiContext& g = *GImGui;
8904
284
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8905
284
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8906
170
        return false;
8907
114
    const float t = g.IO.MouseDownDuration[button];
8908
114
    if (t < 0.0f)
8909
0
        return false;
8910
114
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8911
8912
114
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8913
114
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
8914
114
    if (!pressed)
8915
70
        return false;
8916
8917
44
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
8918
0
        return false;
8919
8920
44
    return true;
8921
44
}
8922
8923
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
8924
0
{
8925
0
    ImGuiContext& g = *GImGui;
8926
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8927
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
8928
0
}
8929
8930
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
8931
280
{
8932
280
    ImGuiContext& g = *GImGui;
8933
280
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8934
280
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
8935
280
}
8936
8937
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
8938
1
{
8939
1
    ImGuiContext& g = *GImGui;
8940
1
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8941
1
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
8942
1
}
8943
8944
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
8945
0
{
8946
0
    ImGuiContext& g = *GImGui;
8947
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8948
0
    return g.IO.MouseClickedCount[button];
8949
0
}
8950
8951
// Test if mouse cursor is hovering given rectangle
8952
// NB- Rectangle is clipped by our current clip setting
8953
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
8954
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
8955
111k
{
8956
111k
    ImGuiContext& g = *GImGui;
8957
8958
    // Clip
8959
111k
    ImRect rect_clipped(r_min, r_max);
8960
111k
    if (clip)
8961
66.0k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
8962
8963
    // Expand for touch input
8964
111k
    const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
8965
111k
    if (!rect_for_touch.Contains(g.IO.MousePos))
8966
110k
        return false;
8967
1.43k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
8968
1
        return false;
8969
1.43k
    return true;
8970
1.43k
}
8971
8972
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
8973
// [Internal] This doesn't test if the button is pressed
8974
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
8975
122
{
8976
122
    ImGuiContext& g = *GImGui;
8977
122
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8978
122
    if (lock_threshold < 0.0f)
8979
119
        lock_threshold = g.IO.MouseDragThreshold;
8980
122
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
8981
122
}
8982
8983
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
8984
123
{
8985
123
    ImGuiContext& g = *GImGui;
8986
123
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8987
123
    if (!g.IO.MouseDown[button])
8988
1
        return false;
8989
122
    return IsMouseDragPastThreshold(button, lock_threshold);
8990
123
}
8991
8992
ImVec2 ImGui::GetMousePos()
8993
1.36k
{
8994
1.36k
    ImGuiContext& g = *GImGui;
8995
1.36k
    return g.IO.MousePos;
8996
1.36k
}
8997
8998
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
8999
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
9000
0
{
9001
0
    ImGuiContext& g = *GImGui;
9002
0
    if (g.BeginPopupStack.Size > 0)
9003
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
9004
0
    return g.IO.MousePos;
9005
0
}
9006
9007
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
9008
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
9009
53.7k
{
9010
    // The assert is only to silence a false-positive in XCode Static Analysis.
9011
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
9012
53.7k
    IM_ASSERT(GImGui != NULL);
9013
53.7k
    const float MOUSE_INVALID = -256000.0f;
9014
53.7k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
9015
53.7k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
9016
53.7k
}
9017
9018
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
9019
bool ImGui::IsAnyMouseDown()
9020
0
{
9021
0
    ImGuiContext& g = *GImGui;
9022
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
9023
0
        if (g.IO.MouseDown[n])
9024
0
            return true;
9025
0
    return false;
9026
0
}
9027
9028
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
9029
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
9030
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
9031
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
9032
0
{
9033
0
    ImGuiContext& g = *GImGui;
9034
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9035
0
    if (lock_threshold < 0.0f)
9036
0
        lock_threshold = g.IO.MouseDragThreshold;
9037
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
9038
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
9039
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
9040
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
9041
0
    return ImVec2(0.0f, 0.0f);
9042
0
}
9043
9044
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
9045
0
{
9046
0
    ImGuiContext& g = *GImGui;
9047
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
9048
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
9049
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
9050
0
}
9051
9052
// Get desired mouse cursor shape.
9053
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
9054
// updated during the frame, and locked in EndFrame()/Render().
9055
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
9056
ImGuiMouseCursor ImGui::GetMouseCursor()
9057
0
{
9058
0
    ImGuiContext& g = *GImGui;
9059
0
    return g.MouseCursor;
9060
0
}
9061
9062
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
9063
0
{
9064
0
    ImGuiContext& g = *GImGui;
9065
0
    g.MouseCursor = cursor_type;
9066
0
}
9067
9068
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
9069
126k
{
9070
126k
    IM_ASSERT(ImGui::IsAliasKey(key));
9071
126k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
9072
126k
    key_data->Down = v;
9073
126k
    key_data->AnalogValue = analog_value;
9074
126k
}
9075
9076
// [Internal] Do not use directly
9077
static ImGuiKeyChord GetMergedModsFromKeys()
9078
36.0k
{
9079
36.0k
    ImGuiKeyChord mods = 0;
9080
36.0k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
9081
36.0k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
9082
36.0k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
9083
36.0k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
9084
36.0k
    return mods;
9085
36.0k
}
9086
9087
static void ImGui::UpdateKeyboardInputs()
9088
18.0k
{
9089
18.0k
    ImGuiContext& g = *GImGui;
9090
18.0k
    ImGuiIO& io = g.IO;
9091
9092
    // Import legacy keys or verify they are not used
9093
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9094
    if (io.BackendUsingLegacyKeyArrays == 0)
9095
    {
9096
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
9097
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
9098
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
9099
    }
9100
    else
9101
    {
9102
        if (g.FrameCount == 0)
9103
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9104
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
9105
9106
        // Build reverse KeyMap (Named -> Legacy)
9107
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
9108
            if (io.KeyMap[n] != -1)
9109
            {
9110
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
9111
                io.KeyMap[io.KeyMap[n]] = n;
9112
            }
9113
9114
        // Import legacy keys into new ones
9115
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
9116
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
9117
            {
9118
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
9119
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
9120
                io.KeysData[key].Down = io.KeysDown[n];
9121
                if (key != n)
9122
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
9123
                io.BackendUsingLegacyKeyArrays = 1;
9124
            }
9125
        if (io.BackendUsingLegacyKeyArrays == 1)
9126
        {
9127
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
9128
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
9129
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
9130
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
9131
        }
9132
    }
9133
9134
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9135
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
9136
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
9137
    {
9138
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
9139
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
9140
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
9141
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
9142
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
9143
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
9144
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
9145
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
9146
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
9147
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
9148
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
9149
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
9150
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
9151
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
9152
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
9153
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
9154
        #undef NAV_MAP_KEY
9155
    }
9156
#endif
9157
#endif
9158
9159
    // Update aliases
9160
108k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
9161
90.0k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
9162
18.0k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
9163
18.0k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
9164
9165
    // Synchronize io.KeyMods and io.KeyXXX values.
9166
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9167
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
9168
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
9169
18.0k
    io.KeyMods = GetMergedModsFromKeys();
9170
18.0k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
9171
18.0k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
9172
18.0k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
9173
18.0k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
9174
9175
    // Clear gamepad data if disabled
9176
18.0k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
9177
450k
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
9178
432k
        {
9179
432k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
9180
432k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
9181
432k
        }
9182
9183
    // Update keys
9184
2.53M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
9185
2.52M
    {
9186
2.52M
        ImGuiKeyData* key_data = &io.KeysData[i];
9187
2.52M
        key_data->DownDurationPrev = key_data->DownDuration;
9188
2.52M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
9189
2.52M
    }
9190
9191
    // Update keys/input owner (named keys only): one entry per key
9192
2.53M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
9193
2.52M
    {
9194
2.52M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
9195
2.52M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
9196
2.52M
        owner_data->OwnerCurr = owner_data->OwnerNext;
9197
2.52M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
9198
2.51M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
9199
2.52M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
9200
2.52M
    }
9201
9202
18.0k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
9203
18.0k
}
9204
9205
static void ImGui::UpdateMouseInputs()
9206
18.0k
{
9207
18.0k
    ImGuiContext& g = *GImGui;
9208
18.0k
    ImGuiIO& io = g.IO;
9209
9210
    // Mouse Wheel swapping flag
9211
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9212
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9213
    // - FIXME: However this means when running on OSX over Emscripten, Shift+WheelY will incur two swapping (1 in OS, 1 here), canceling the feature.
9214
    // - FIXME: When we can distinguish e.g. touchpad scroll events from mouse ones, we'll set this accordingly based on input source.
9215
18.0k
    io.MouseWheelRequestAxisSwap = io.KeyShift && !io.ConfigMacOSXBehaviors;
9216
9217
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
9218
18.0k
    if (IsMousePosValid(&io.MousePos))
9219
3.46k
        io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);
9220
9221
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
9222
18.0k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
9223
3.06k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
9224
14.9k
    else
9225
14.9k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
9226
9227
    // Update stationary timer.
9228
    // FIXME: May need to rework again to have some tolerance for occasional small movement, while being functional on high-framerates.
9229
18.0k
    const float mouse_stationary_threshold = (io.MouseSource == ImGuiMouseSource_Mouse) ? 2.0f : 3.0f; // Slightly higher threshold for ImGuiMouseSource_TouchScreen/ImGuiMouseSource_Pen, may need rework.
9230
18.0k
    const bool mouse_stationary = (ImLengthSqr(io.MouseDelta) <= mouse_stationary_threshold * mouse_stationary_threshold);
9231
18.0k
    g.MouseStationaryTimer = mouse_stationary ? (g.MouseStationaryTimer + io.DeltaTime) : 0.0f;
9232
    //IMGUI_DEBUG_LOG("%.4f\n", g.MouseStationaryTimer);
9233
9234
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
9235
18.0k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
9236
281
        g.NavDisableMouseHover = false;
9237
9238
18.0k
    io.MousePosPrev = io.MousePos;
9239
108k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
9240
90.0k
    {
9241
90.0k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
9242
90.0k
        io.MouseClickedCount[i] = 0; // Will be filled below
9243
90.0k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
9244
90.0k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
9245
90.0k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
9246
90.0k
        if (io.MouseClicked[i])
9247
789
        {
9248
789
            bool is_repeated_click = false;
9249
789
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
9250
390
            {
9251
390
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9252
390
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
9253
337
                    is_repeated_click = true;
9254
390
            }
9255
789
            if (is_repeated_click)
9256
337
                io.MouseClickedLastCount[i]++;
9257
452
            else
9258
452
                io.MouseClickedLastCount[i] = 1;
9259
789
            io.MouseClickedTime[i] = g.Time;
9260
789
            io.MouseClickedPos[i] = io.MousePos;
9261
789
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
9262
789
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9263
789
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9264
789
        }
9265
89.2k
        else if (io.MouseDown[i])
9266
4.27k
        {
9267
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9268
4.27k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9269
4.27k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9270
4.27k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9271
4.27k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9272
4.27k
        }
9273
9274
        // We provide io.MouseDoubleClicked[] as a legacy service
9275
90.0k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9276
9277
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9278
90.0k
        if (io.MouseClicked[i])
9279
789
            g.NavDisableMouseHover = false;
9280
90.0k
    }
9281
18.0k
}
9282
9283
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9284
20
{
9285
20
    ImGuiContext& g = *GImGui;
9286
20
    if (window)
9287
11
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9288
9
    else
9289
9
        g.WheelingWindowReleaseTimer = 0.0f;
9290
20
    if (g.WheelingWindow == window)
9291
2
        return;
9292
18
    IMGUI_DEBUG_LOG_IO("[io] LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9293
18
    g.WheelingWindow = window;
9294
18
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9295
18
    if (window == NULL)
9296
9
    {
9297
9
        g.WheelingWindowStartFrame = -1;
9298
9
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9299
9
    }
9300
18
}
9301
9302
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9303
9
{
9304
    // For each axis, find window in the hierarchy that may want to use scrolling
9305
9
    ImGuiContext& g = *GImGui;
9306
9
    ImGuiWindow* windows[2] = { NULL, NULL };
9307
27
    for (int axis = 0; axis < 2; axis++)
9308
18
        if (wheel[axis] != 0.0f)
9309
14
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9310
0
            {
9311
                // Bubble up into parent window if:
9312
                // - a child window doesn't allow any scrolling.
9313
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9314
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9315
0
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9316
0
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9317
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9318
0
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9319
0
                    break; // select this window
9320
0
            }
9321
9
    if (windows[0] == NULL && windows[1] == NULL)
9322
0
        return NULL;
9323
9324
    // If there's only one window or only one axis then there's no ambiguity
9325
9
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9326
9
        return windows[1] ? windows[1] : windows[0];
9327
9328
    // If candidate are different windows we need to decide which one to prioritize
9329
    // - First frame: only find a winner if one axis is zero.
9330
    // - Subsequent frames: only find a winner when one is more than the other.
9331
0
    if (g.WheelingWindowStartFrame == -1)
9332
0
        g.WheelingWindowStartFrame = g.FrameCount;
9333
0
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9334
0
    {
9335
0
        g.WheelingWindowWheelRemainder = wheel;
9336
0
        return NULL;
9337
0
    }
9338
0
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9339
0
}
9340
9341
// Called by NewFrame()
9342
void ImGui::UpdateMouseWheel()
9343
18.0k
{
9344
    // Reset the locked window if we move the mouse or after the timer elapses.
9345
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9346
18.0k
    ImGuiContext& g = *GImGui;
9347
18.0k
    if (g.WheelingWindow != NULL)
9348
91
    {
9349
91
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9350
91
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9351
3
            g.WheelingWindowReleaseTimer = 0.0f;
9352
91
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9353
9
            LockWheelingWindow(NULL, 0.0f);
9354
91
    }
9355
9356
18.0k
    ImVec2 wheel;
9357
18.0k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9358
18.0k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9359
9360
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9361
18.0k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9362
18.0k
    if (!mouse_window || mouse_window->Collapsed)
9363
17.6k
        return;
9364
9365
    // Zoom / Scale window
9366
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9367
380
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9368
0
    {
9369
0
        LockWheelingWindow(mouse_window, wheel.y);
9370
0
        ImGuiWindow* window = mouse_window;
9371
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9372
0
        const float scale = new_font_scale / window->FontWindowScale;
9373
0
        window->FontWindowScale = new_font_scale;
9374
0
        if (window == window->RootWindow)
9375
0
        {
9376
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9377
0
            SetWindowPos(window, window->Pos + offset, 0);
9378
0
            window->Size = ImFloor(window->Size * scale);
9379
0
            window->SizeFull = ImFloor(window->SizeFull * scale);
9380
0
        }
9381
0
        return;
9382
0
    }
9383
380
    if (g.IO.KeyCtrl)
9384
0
        return;
9385
9386
    // Mouse wheel scrolling
9387
    // Read about io.MouseWheelRequestAxisSwap and its issue on Mac+Emscripten in UpdateMouseInputs()
9388
380
    if (g.IO.MouseWheelRequestAxisSwap)
9389
0
        wheel = ImVec2(wheel.y, 0.0f);
9390
9391
    // Maintain a rough average of moving magnitude on both axises
9392
    // FIXME: should by based on wall clock time rather than frame-counter
9393
380
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9394
380
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9395
9396
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9397
380
    wheel += g.WheelingWindowWheelRemainder;
9398
380
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9399
380
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9400
369
        return;
9401
9402
    // Mouse wheel scrolling: find target and apply
9403
    // - don't renew lock if axis doesn't apply on the window.
9404
    // - select a main axis when both axises are being moved.
9405
11
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9406
11
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9407
11
        {
9408
11
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9409
11
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9410
7
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9411
11
            if (do_scroll[ImGuiAxis_X])
9412
7
            {
9413
7
                LockWheelingWindow(window, wheel.x);
9414
7
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9415
7
                float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
9416
7
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9417
7
            }
9418
11
            if (do_scroll[ImGuiAxis_Y])
9419
4
            {
9420
4
                LockWheelingWindow(window, wheel.y);
9421
4
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9422
4
                float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
9423
4
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9424
4
            }
9425
11
        }
9426
11
}
9427
9428
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9429
0
{
9430
0
    ImGuiContext& g = *GImGui;
9431
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9432
0
}
9433
9434
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9435
0
{
9436
0
    ImGuiContext& g = *GImGui;
9437
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9438
0
}
9439
9440
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9441
static const char* GetInputSourceName(ImGuiInputSource source)
9442
0
{
9443
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Clipboard" };
9444
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9445
0
    return input_source_names[source];
9446
0
}
9447
static const char* GetMouseSourceName(ImGuiMouseSource source)
9448
0
{
9449
0
    const char* mouse_source_names[] = { "Mouse", "TouchScreen", "Pen" };
9450
0
    IM_ASSERT(IM_ARRAYSIZE(mouse_source_names) == ImGuiMouseSource_COUNT && source >= 0 && source < ImGuiMouseSource_COUNT);
9451
0
    return mouse_source_names[source];
9452
0
}
9453
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9454
0
{
9455
0
    ImGuiContext& g = *GImGui;
9456
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("[io] %s: MousePos (%.1f, %.1f) (%s)\n", prefix, e->MousePos.PosX, e->MousePos.PosY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9457
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("[io] %s: MouseButton %d %s (%s)\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up", GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9458
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("[io] %s: MouseWheel (%.3f, %.3f) (%s)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY, GetMouseSourceName(e->MouseWheel.MouseSource)); return; }
9459
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("[io] %s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9460
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("[io] %s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9461
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("[io] %s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9462
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("[io] %s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9463
0
}
9464
#endif
9465
9466
// Process input queue
9467
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9468
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9469
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9470
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9471
18.0k
{
9472
18.0k
    ImGuiContext& g = *GImGui;
9473
18.0k
    ImGuiIO& io = g.IO;
9474
9475
    // Only trickle chars<>key when working with InputText()
9476
    // FIXME: InputText() could parse event trail?
9477
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9478
18.0k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9479
9480
18.0k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9481
18.0k
    int  mouse_button_changed = 0x00;
9482
18.0k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9483
9484
18.0k
    int event_n = 0;
9485
24.0k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9486
6.99k
    {
9487
6.99k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9488
6.99k
        if (e->Type == ImGuiInputEventType_MousePos)
9489
1.06k
        {
9490
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9491
1.06k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9492
1.06k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9493
109
                break;
9494
953
            io.MousePos = event_pos;
9495
953
            io.MouseSource = e->MousePos.MouseSource;
9496
953
            mouse_moved = true;
9497
953
        }
9498
5.92k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9499
1.43k
        {
9500
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9501
1.43k
            const ImGuiMouseButton button = e->MouseButton.Button;
9502
1.43k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9503
1.43k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9504
345
                break;
9505
1.08k
            if (trickle_fast_inputs && e->MouseButton.MouseSource == ImGuiMouseSource_TouchScreen && mouse_moved) // #2702: TouchScreen have no initial hover.
9506
0
                break;
9507
1.08k
            io.MouseDown[button] = e->MouseButton.Down;
9508
1.08k
            io.MouseSource = e->MouseButton.MouseSource;
9509
1.08k
            mouse_button_changed |= (1 << button);
9510
1.08k
        }
9511
4.49k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9512
333
        {
9513
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9514
333
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9515
72
                break;
9516
261
            io.MouseWheelH += e->MouseWheel.WheelX;
9517
261
            io.MouseWheel += e->MouseWheel.WheelY;
9518
261
            io.MouseSource = e->MouseWheel.MouseSource;
9519
261
            mouse_wheeled = true;
9520
261
        }
9521
4.16k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9522
0
        {
9523
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9524
0
        }
9525
4.16k
        else if (e->Type == ImGuiInputEventType_Key)
9526
983
        {
9527
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9528
983
            ImGuiKey key = e->Key.Key;
9529
983
            IM_ASSERT(key != ImGuiKey_None);
9530
983
            ImGuiKeyData* key_data = GetKeyData(key);
9531
983
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9532
983
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9533
170
                break;
9534
813
            key_data->Down = e->Key.Down;
9535
813
            key_data->AnalogValue = e->Key.AnalogValue;
9536
813
            key_changed = true;
9537
813
            key_changed_mask.SetBit(key_data_index);
9538
9539
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9540
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9541
            io.KeysDown[key_data_index] = key_data->Down;
9542
            if (io.KeyMap[key_data_index] != -1)
9543
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9544
#endif
9545
813
        }
9546
3.17k
        else if (e->Type == ImGuiInputEventType_Text)
9547
2.87k
        {
9548
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9549
2.87k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9550
240
                break;
9551
2.63k
            unsigned int c = e->Text.Char;
9552
2.63k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9553
2.63k
            if (trickle_interleaved_keys_and_text)
9554
0
                text_inputted = true;
9555
2.63k
        }
9556
307
        else if (e->Type == ImGuiInputEventType_Focus)
9557
307
        {
9558
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9559
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9560
307
            const bool focus_lost = !e->AppFocused.Focused;
9561
307
            io.AppFocusLost = focus_lost;
9562
307
        }
9563
0
        else
9564
0
        {
9565
0
            IM_ASSERT(0 && "Unknown event!");
9566
0
        }
9567
6.99k
    }
9568
9569
    // Record trail (for domain-specific applications wanting to access a precise trail)
9570
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9571
24.0k
    for (int n = 0; n < event_n; n++)
9572
6.05k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9573
9574
    // [DEBUG]
9575
18.0k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9576
18.0k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9577
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9578
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9579
18.0k
#endif
9580
9581
    // Remaining events will be processed on the next frame
9582
18.0k
    if (event_n == g.InputEventsQueue.Size)
9583
17.0k
        g.InputEventsQueue.resize(0);
9584
936
    else
9585
936
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9586
9587
    // Clear buttons state when focus is lost
9588
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9589
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9590
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9591
18.0k
    if (g.IO.AppFocusLost)
9592
209
        g.IO.ClearInputKeys();
9593
18.0k
}
9594
9595
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9596
0
{
9597
0
    if (!IsNamedKeyOrModKey(key))
9598
0
        return ImGuiKeyOwner_None;
9599
9600
0
    ImGuiContext& g = *GImGui;
9601
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9602
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9603
9604
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9605
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9606
0
            return ImGuiKeyOwner_None;
9607
9608
0
    return owner_id;
9609
0
}
9610
9611
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9612
// TestKeyOwner(..., None) : (owner == None)
9613
// TestKeyOwner(..., Any)  : no owner test
9614
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9615
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9616
42.0k
{
9617
42.0k
    if (!IsNamedKeyOrModKey(key))
9618
0
        return true;
9619
9620
42.0k
    ImGuiContext& g = *GImGui;
9621
42.0k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9622
58
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9623
8
            return false;
9624
9625
42.0k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9626
42.0k
    if (owner_id == ImGuiKeyOwner_Any)
9627
5.29k
        return (owner_data->LockThisFrame == false);
9628
9629
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9630
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9631
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9632
36.7k
    if (owner_data->OwnerCurr != owner_id)
9633
43
    {
9634
43
        if (owner_data->LockThisFrame)
9635
0
            return false;
9636
43
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9637
0
            return false;
9638
43
    }
9639
9640
36.7k
    return true;
9641
36.7k
}
9642
9643
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9644
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9645
// - SetKeyOwner(..., None)              : clears owner
9646
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9647
// - SetKeyOwner(..., Any or None, Lock) : set lock
9648
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9649
44
{
9650
44
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9651
44
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9652
9653
44
    ImGuiContext& g = *GImGui;
9654
44
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
9655
44
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9656
9657
    // We cannot lock by default as it would likely break lots of legacy code.
9658
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9659
44
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9660
44
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9661
44
}
9662
9663
// Rarely used helper
9664
void ImGui::SetKeyOwnersForKeyChord(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9665
0
{
9666
0
    if (key_chord & ImGuiMod_Ctrl)      { SetKeyOwner(ImGuiMod_Ctrl, owner_id, flags); }
9667
0
    if (key_chord & ImGuiMod_Shift)     { SetKeyOwner(ImGuiMod_Shift, owner_id, flags); }
9668
0
    if (key_chord & ImGuiMod_Alt)       { SetKeyOwner(ImGuiMod_Alt, owner_id, flags); }
9669
0
    if (key_chord & ImGuiMod_Super)     { SetKeyOwner(ImGuiMod_Super, owner_id, flags); }
9670
0
    if (key_chord & ImGuiMod_Shortcut)  { SetKeyOwner(ImGuiMod_Shortcut, owner_id, flags); }
9671
0
    if (key_chord & ~ImGuiMod_Mask_)    { SetKeyOwner((ImGuiKey)(key_chord & ~ImGuiMod_Mask_), owner_id, flags); }
9672
0
}
9673
9674
// This is more or less equivalent to:
9675
//   if (IsItemHovered() || IsItemActive())
9676
//       SetKeyOwner(key, GetItemID());
9677
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9678
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9679
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9680
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9681
0
{
9682
0
    ImGuiContext& g = *GImGui;
9683
0
    ImGuiID id = g.LastItemData.ID;
9684
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9685
0
        return;
9686
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9687
0
        flags |= ImGuiInputFlags_CondDefault_;
9688
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9689
0
    {
9690
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9691
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9692
0
    }
9693
0
}
9694
9695
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9696
36.0k
{
9697
36.0k
    ImGuiContext& g = *GImGui;
9698
9699
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9700
36.0k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9701
36.0k
        flags |= ImGuiInputFlags_RouteFocused;
9702
36.0k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9703
0
        return false;
9704
9705
36.0k
    if (key_chord & ImGuiMod_Shortcut)
9706
0
        key_chord = ConvertShortcutMod(key_chord);
9707
36.0k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9708
36.0k
    if (g.IO.KeyMods != mods)
9709
36.0k
        return false;
9710
9711
    // Special storage location for mods
9712
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9713
0
    if (key == ImGuiKey_None)
9714
0
        key = ConvertSingleModFlagToKey(&g, mods);
9715
9716
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9717
0
        return false;
9718
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9719
9720
0
    return true;
9721
0
}
9722
9723
9724
//-----------------------------------------------------------------------------
9725
// [SECTION] ERROR CHECKING
9726
//-----------------------------------------------------------------------------
9727
9728
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9729
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9730
// If this triggers you have an issue:
9731
// - Most commonly: mismatched headers and compiled code version.
9732
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9733
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9734
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9735
//   Otherwise it is possible that different compilation units would see different structure layout
9736
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9737
1
{
9738
1
    bool error = false;
9739
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9740
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9741
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9742
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9743
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9744
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9745
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9746
1
    return !error;
9747
1
}
9748
9749
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9750
// This is causing issues and ambiguity and we need to retire that.
9751
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9752
// [Scenario 1]
9753
//  Previously this would make the window content size ~200x200:
9754
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9755
//  Instead, please submit an item:
9756
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9757
//  Alternative:
9758
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9759
// [Scenario 2]
9760
//  For reference this is one of the issue what we aim to fix with this change:
9761
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9762
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9763
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9764
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9765
0
{
9766
0
    ImGuiContext& g = *GImGui;
9767
0
    ImGuiWindow* window = g.CurrentWindow;
9768
0
    IM_ASSERT(window->DC.IsSetPos);
9769
0
    window->DC.IsSetPos = false;
9770
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9771
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9772
0
        return;
9773
0
    if (window->SkipItems)
9774
0
        return;
9775
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9776
#else
9777
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9778
#endif
9779
0
}
9780
9781
static void ImGui::ErrorCheckNewFrameSanityChecks()
9782
18.0k
{
9783
18.0k
    ImGuiContext& g = *GImGui;
9784
9785
    // Check user IM_ASSERT macro
9786
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9787
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9788
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9789
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9790
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9791
18.0k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9792
9793
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9794
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9795
#ifdef __EMSCRIPTEN__
9796
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9797
        g.IO.DeltaTime = 0.00001f;
9798
#endif
9799
9800
    // Check user data
9801
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9802
18.0k
    IM_ASSERT(g.Initialized);
9803
18.0k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9804
18.0k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9805
18.0k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9806
18.0k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9807
18.0k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9808
18.0k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9809
18.0k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9810
18.0k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9811
18.0k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9812
18.0k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9813
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9814
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9815
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9816
9817
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9818
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9819
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9820
#endif
9821
9822
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9823
18.0k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
9824
1
        g.IO.ConfigWindowsResizeFromEdges = false;
9825
9826
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
9827
18.0k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
9828
18.0k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9829
18.0k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
9830
18.0k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9831
9832
    // Perform simple checks: multi-viewport and platform windows support
9833
18.0k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
9834
1
    {
9835
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
9836
0
        {
9837
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
9838
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
9839
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
9840
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
9841
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
9842
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
9843
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
9844
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
9845
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
9846
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
9847
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
9848
0
        }
9849
1
        else
9850
1
        {
9851
            // Disable feature, our backends do not support it
9852
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
9853
1
        }
9854
9855
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
9856
1
        for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
9857
0
        {
9858
0
            ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
9859
0
            IM_UNUSED(mon);
9860
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
9861
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
9862
0
            IM_ASSERT(mon.DpiScale != 0.0f);
9863
0
        }
9864
1
    }
9865
18.0k
}
9866
9867
static void ImGui::ErrorCheckEndFrameSanityChecks()
9868
18.0k
{
9869
18.0k
    ImGuiContext& g = *GImGui;
9870
9871
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
9872
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
9873
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
9874
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
9875
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
9876
    // while still correctly asserting on mid-frame key press events.
9877
18.0k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
9878
18.0k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
9879
18.0k
    IM_UNUSED(key_mods);
9880
9881
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
9882
    //ErrorCheckEndFrameRecover();
9883
9884
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
9885
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
9886
18.0k
    if (g.CurrentWindowStack.Size != 1)
9887
0
    {
9888
0
        if (g.CurrentWindowStack.Size > 1)
9889
0
        {
9890
0
            ImGuiWindow* window = g.CurrentWindowStack.back().Window; // <-- This window was not Ended!
9891
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
9892
0
            IM_UNUSED(window);
9893
0
            while (g.CurrentWindowStack.Size > 1)
9894
0
                End();
9895
0
        }
9896
0
        else
9897
0
        {
9898
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
9899
0
        }
9900
0
    }
9901
9902
18.0k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
9903
18.0k
}
9904
9905
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
9906
// Must be called during or before EndFrame().
9907
// This is generally flawed as we are not necessarily End/Popping things in the right order.
9908
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
9909
// FIXME: Can't recover from interleaved BeginTabBar/Begin
9910
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9911
0
{
9912
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
9913
0
    ImGuiContext& g = *GImGui;
9914
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
9915
0
    {
9916
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
9917
0
        ImGuiWindow* window = g.CurrentWindow;
9918
0
        if (g.CurrentWindowStack.Size == 1)
9919
0
        {
9920
0
            IM_ASSERT(window->IsFallbackWindow);
9921
0
            break;
9922
0
        }
9923
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
9924
0
        {
9925
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
9926
0
            EndChild();
9927
0
        }
9928
0
        else
9929
0
        {
9930
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
9931
0
            End();
9932
0
        }
9933
0
    }
9934
0
}
9935
9936
// Must be called before End()/EndChild()
9937
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9938
0
{
9939
0
    ImGuiContext& g = *GImGui;
9940
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
9941
0
    {
9942
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
9943
0
        EndTable();
9944
0
    }
9945
9946
0
    ImGuiWindow* window = g.CurrentWindow;
9947
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
9948
0
    IM_ASSERT(window != NULL);
9949
0
    while (g.CurrentTabBar != NULL) //-V1044
9950
0
    {
9951
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
9952
0
        EndTabBar();
9953
0
    }
9954
0
    while (window->DC.TreeDepth > 0)
9955
0
    {
9956
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
9957
0
        TreePop();
9958
0
    }
9959
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
9960
0
    {
9961
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
9962
0
        EndGroup();
9963
0
    }
9964
0
    while (window->IDStack.Size > 1)
9965
0
    {
9966
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
9967
0
        PopID();
9968
0
    }
9969
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
9970
0
    {
9971
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
9972
0
        EndDisabled();
9973
0
    }
9974
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
9975
0
    {
9976
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
9977
0
        PopStyleColor();
9978
0
    }
9979
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
9980
0
    {
9981
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
9982
0
        PopItemFlag();
9983
0
    }
9984
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
9985
0
    {
9986
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
9987
0
        PopStyleVar();
9988
0
    }
9989
0
    while (g.FontStack.Size > stack_sizes->SizeOfFontStack) //-V1044
9990
0
    {
9991
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFont() in '%s'", window->Name);
9992
0
        PopFont();
9993
0
    }
9994
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
9995
0
    {
9996
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
9997
0
        PopFocusScope();
9998
0
    }
9999
0
}
10000
10001
// Save current stack sizes for later compare
10002
void ImGuiStackSizes::SetToContextState(ImGuiContext* ctx)
10003
45.5k
{
10004
45.5k
    ImGuiContext& g = *ctx;
10005
45.5k
    ImGuiWindow* window = g.CurrentWindow;
10006
45.5k
    SizeOfIDStack = (short)window->IDStack.Size;
10007
45.5k
    SizeOfColorStack = (short)g.ColorStack.Size;
10008
45.5k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
10009
45.5k
    SizeOfFontStack = (short)g.FontStack.Size;
10010
45.5k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
10011
45.5k
    SizeOfGroupStack = (short)g.GroupStack.Size;
10012
45.5k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
10013
45.5k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
10014
45.5k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
10015
45.5k
}
10016
10017
// Compare to detect usage errors
10018
void ImGuiStackSizes::CompareWithContextState(ImGuiContext* ctx)
10019
45.5k
{
10020
45.5k
    ImGuiContext& g = *ctx;
10021
45.5k
    ImGuiWindow* window = g.CurrentWindow;
10022
45.5k
    IM_UNUSED(window);
10023
10024
    // Window stacks
10025
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
10026
45.5k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
10027
10028
    // Global stacks
10029
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
10030
45.5k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
10031
45.5k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
10032
45.5k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
10033
45.5k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
10034
45.5k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
10035
45.5k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
10036
45.5k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
10037
45.5k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
10038
45.5k
}
10039
10040
10041
//-----------------------------------------------------------------------------
10042
// [SECTION] LAYOUT
10043
//-----------------------------------------------------------------------------
10044
// - ItemSize()
10045
// - ItemAdd()
10046
// - SameLine()
10047
// - GetCursorScreenPos()
10048
// - SetCursorScreenPos()
10049
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
10050
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
10051
// - GetCursorStartPos()
10052
// - Indent()
10053
// - Unindent()
10054
// - SetNextItemWidth()
10055
// - PushItemWidth()
10056
// - PushMultiItemsWidths()
10057
// - PopItemWidth()
10058
// - CalcItemWidth()
10059
// - CalcItemSize()
10060
// - GetTextLineHeight()
10061
// - GetTextLineHeightWithSpacing()
10062
// - GetFrameHeight()
10063
// - GetFrameHeightWithSpacing()
10064
// - GetContentRegionMax()
10065
// - GetContentRegionMaxAbs() [Internal]
10066
// - GetContentRegionAvail(),
10067
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
10068
// - BeginGroup()
10069
// - EndGroup()
10070
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
10071
//-----------------------------------------------------------------------------
10072
10073
// Advance cursor given item size for layout.
10074
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
10075
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
10076
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
10077
18.0k
{
10078
18.0k
    ImGuiContext& g = *GImGui;
10079
18.0k
    ImGuiWindow* window = g.CurrentWindow;
10080
18.0k
    if (window->SkipItems)
10081
0
        return;
10082
10083
    // We increase the height in this function to accommodate for baseline offset.
10084
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
10085
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
10086
18.0k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
10087
10088
18.0k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
10089
18.0k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
10090
10091
    // Always align ourselves on pixel boundaries
10092
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
10093
18.0k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
10094
18.0k
    window->DC.CursorPosPrevLine.y = line_y1;
10095
18.0k
    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
10096
18.0k
    window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
10097
18.0k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
10098
18.0k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
10099
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
10100
10101
18.0k
    window->DC.PrevLineSize.y = line_height;
10102
18.0k
    window->DC.CurrLineSize.y = 0.0f;
10103
18.0k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
10104
18.0k
    window->DC.CurrLineTextBaseOffset = 0.0f;
10105
18.0k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
10106
10107
    // Horizontal layout mode
10108
18.0k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
10109
0
        SameLine();
10110
18.0k
}
10111
10112
// Declare item bounding box for clipping and interaction.
10113
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
10114
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
10115
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
10116
75.1k
{
10117
75.1k
    ImGuiContext& g = *GImGui;
10118
75.1k
    ImGuiWindow* window = g.CurrentWindow;
10119
10120
    // Set item data
10121
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
10122
75.1k
    g.LastItemData.ID = id;
10123
75.1k
    g.LastItemData.Rect = bb;
10124
75.1k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
10125
75.1k
    g.LastItemData.InFlags = g.CurrentItemFlags | g.NextItemData.ItemFlags | extra_flags;
10126
75.1k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
10127
10128
    // Directional navigation processing
10129
75.1k
    if (id != 0)
10130
65.7k
    {
10131
65.7k
        KeepAliveID(id);
10132
10133
        // Runs prior to clipping early-out
10134
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
10135
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
10136
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
10137
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
10138
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
10139
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
10140
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
10141
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
10142
65.7k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
10143
44.7k
        {
10144
44.7k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
10145
44.7k
            if (g.NavId == id || g.NavAnyRequest)
10146
637
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
10147
245
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
10148
245
                        NavProcessItem();
10149
44.7k
        }
10150
10151
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
10152
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
10153
        // READ THE FAQ: https://dearimgui.com/faq
10154
65.7k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
10155
65.7k
    }
10156
75.1k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
10157
75.1k
    g.NextItemData.ItemFlags = ImGuiItemFlags_None;
10158
10159
#ifdef IMGUI_ENABLE_TEST_ENGINE
10160
    if (id != 0)
10161
        IMGUI_TEST_ENGINE_ITEM_ADD(id, g.LastItemData.NavRect, &g.LastItemData);
10162
#endif
10163
10164
    // Clipping test
10165
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
10166
    //const bool is_clipped = IsClippedEx(bb, id);
10167
    //if (is_clipped)
10168
    //    return false;
10169
75.1k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
10170
75.1k
    if (!is_rect_visible)
10171
10.2k
        if (id == 0 || (id != g.ActiveId && id != g.ActiveIdPreviousFrame && id != g.NavId))
10172
10.2k
            if (!g.LogEnabled)
10173
10.2k
                return false;
10174
10175
    // [DEBUG]
10176
64.8k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
10177
64.8k
    if (id != 0 && id == g.DebugLocateId)
10178
0
        DebugLocateItemResolveWithLastItem();
10179
64.8k
#endif
10180
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
10181
    //if ((g.LastItemData.InFlags & ImGuiItemFlags_NoNav) == 0)
10182
    //    window->DrawList->AddRect(g.LastItemData.NavRect.Min, g.LastItemData.NavRect.Max, IM_COL32(255,255,0,255)); // [DEBUG]
10183
10184
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
10185
64.8k
    if (is_rect_visible)
10186
64.8k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
10187
64.8k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
10188
548
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
10189
64.8k
    return true;
10190
75.1k
}
10191
10192
// Gets back to previous line and continue with horizontal layout
10193
//      offset_from_start_x == 0 : follow right after previous item
10194
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
10195
//      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0
10196
//      spacing_w >= 0           : enforce spacing amount
10197
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
10198
0
{
10199
0
    ImGuiContext& g = *GImGui;
10200
0
    ImGuiWindow* window = g.CurrentWindow;
10201
0
    if (window->SkipItems)
10202
0
        return;
10203
10204
0
    if (offset_from_start_x != 0.0f)
10205
0
    {
10206
0
        if (spacing_w < 0.0f)
10207
0
            spacing_w = 0.0f;
10208
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
10209
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10210
0
    }
10211
0
    else
10212
0
    {
10213
0
        if (spacing_w < 0.0f)
10214
0
            spacing_w = g.Style.ItemSpacing.x;
10215
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
10216
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
10217
0
    }
10218
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
10219
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
10220
0
    window->DC.IsSameLine = true;
10221
0
}
10222
10223
ImVec2 ImGui::GetCursorScreenPos()
10224
10.8k
{
10225
10.8k
    ImGuiWindow* window = GetCurrentWindowRead();
10226
10.8k
    return window->DC.CursorPos;
10227
10.8k
}
10228
10229
// 2022/08/05: Setting cursor position also extend boundaries (via modifying CursorMaxPos) used to compute window size, group size etc.
10230
// I believe this was is a judicious choice but it's probably being relied upon (it has been the case since 1.31 and 1.50)
10231
// It would be sane if we requested user to use SetCursorPos() + Dummy(ImVec2(0,0)) to extend CursorMaxPos...
10232
void ImGui::SetCursorScreenPos(const ImVec2& pos)
10233
0
{
10234
0
    ImGuiWindow* window = GetCurrentWindow();
10235
0
    window->DC.CursorPos = pos;
10236
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10237
0
    window->DC.IsSetPos = true;
10238
0
}
10239
10240
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
10241
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
10242
ImVec2 ImGui::GetCursorPos()
10243
0
{
10244
0
    ImGuiWindow* window = GetCurrentWindowRead();
10245
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
10246
0
}
10247
10248
float ImGui::GetCursorPosX()
10249
0
{
10250
0
    ImGuiWindow* window = GetCurrentWindowRead();
10251
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
10252
0
}
10253
10254
float ImGui::GetCursorPosY()
10255
0
{
10256
0
    ImGuiWindow* window = GetCurrentWindowRead();
10257
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
10258
0
}
10259
10260
void ImGui::SetCursorPos(const ImVec2& local_pos)
10261
0
{
10262
0
    ImGuiWindow* window = GetCurrentWindow();
10263
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
10264
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
10265
0
    window->DC.IsSetPos = true;
10266
0
}
10267
10268
void ImGui::SetCursorPosX(float x)
10269
0
{
10270
0
    ImGuiWindow* window = GetCurrentWindow();
10271
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
10272
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
10273
0
    window->DC.IsSetPos = true;
10274
0
}
10275
10276
void ImGui::SetCursorPosY(float y)
10277
0
{
10278
0
    ImGuiWindow* window = GetCurrentWindow();
10279
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
10280
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
10281
0
    window->DC.IsSetPos = true;
10282
0
}
10283
10284
ImVec2 ImGui::GetCursorStartPos()
10285
0
{
10286
0
    ImGuiWindow* window = GetCurrentWindowRead();
10287
0
    return window->DC.CursorStartPos - window->Pos;
10288
0
}
10289
10290
void ImGui::Indent(float indent_w)
10291
0
{
10292
0
    ImGuiContext& g = *GImGui;
10293
0
    ImGuiWindow* window = GetCurrentWindow();
10294
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10295
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10296
0
}
10297
10298
void ImGui::Unindent(float indent_w)
10299
0
{
10300
0
    ImGuiContext& g = *GImGui;
10301
0
    ImGuiWindow* window = GetCurrentWindow();
10302
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10303
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10304
0
}
10305
10306
// Affect large frame+labels widgets only.
10307
void ImGui::SetNextItemWidth(float item_width)
10308
0
{
10309
0
    ImGuiContext& g = *GImGui;
10310
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10311
0
    g.NextItemData.Width = item_width;
10312
0
}
10313
10314
// FIXME: Remove the == 0.0f behavior?
10315
void ImGui::PushItemWidth(float item_width)
10316
0
{
10317
0
    ImGuiContext& g = *GImGui;
10318
0
    ImGuiWindow* window = g.CurrentWindow;
10319
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10320
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10321
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10322
0
}
10323
10324
void ImGui::PushMultiItemsWidths(int components, float w_full)
10325
0
{
10326
0
    ImGuiContext& g = *GImGui;
10327
0
    ImGuiWindow* window = g.CurrentWindow;
10328
0
    const ImGuiStyle& style = g.Style;
10329
0
    const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
10330
0
    const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
10331
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10332
0
    window->DC.ItemWidthStack.push_back(w_item_last);
10333
0
    for (int i = 0; i < components - 2; i++)
10334
0
        window->DC.ItemWidthStack.push_back(w_item_one);
10335
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
10336
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10337
0
}
10338
10339
void ImGui::PopItemWidth()
10340
0
{
10341
0
    ImGuiWindow* window = GetCurrentWindow();
10342
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10343
0
    window->DC.ItemWidthStack.pop_back();
10344
0
}
10345
10346
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10347
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10348
float ImGui::CalcItemWidth()
10349
0
{
10350
0
    ImGuiContext& g = *GImGui;
10351
0
    ImGuiWindow* window = g.CurrentWindow;
10352
0
    float w;
10353
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10354
0
        w = g.NextItemData.Width;
10355
0
    else
10356
0
        w = window->DC.ItemWidth;
10357
0
    if (w < 0.0f)
10358
0
    {
10359
0
        float region_max_x = GetContentRegionMaxAbs().x;
10360
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10361
0
    }
10362
0
    w = IM_FLOOR(w);
10363
0
    return w;
10364
0
}
10365
10366
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10367
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10368
// Note that only CalcItemWidth() is publicly exposed.
10369
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10370
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10371
0
{
10372
0
    ImGuiContext& g = *GImGui;
10373
0
    ImGuiWindow* window = g.CurrentWindow;
10374
10375
0
    ImVec2 region_max;
10376
0
    if (size.x < 0.0f || size.y < 0.0f)
10377
0
        region_max = GetContentRegionMaxAbs();
10378
10379
0
    if (size.x == 0.0f)
10380
0
        size.x = default_w;
10381
0
    else if (size.x < 0.0f)
10382
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10383
10384
0
    if (size.y == 0.0f)
10385
0
        size.y = default_h;
10386
0
    else if (size.y < 0.0f)
10387
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10388
10389
0
    return size;
10390
0
}
10391
10392
float ImGui::GetTextLineHeight()
10393
0
{
10394
0
    ImGuiContext& g = *GImGui;
10395
0
    return g.FontSize;
10396
0
}
10397
10398
float ImGui::GetTextLineHeightWithSpacing()
10399
9.51k
{
10400
9.51k
    ImGuiContext& g = *GImGui;
10401
9.51k
    return g.FontSize + g.Style.ItemSpacing.y;
10402
9.51k
}
10403
10404
float ImGui::GetFrameHeight()
10405
28
{
10406
28
    ImGuiContext& g = *GImGui;
10407
28
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10408
28
}
10409
10410
float ImGui::GetFrameHeightWithSpacing()
10411
0
{
10412
0
    ImGuiContext& g = *GImGui;
10413
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10414
0
}
10415
10416
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10417
10418
// FIXME: This is in window space (not screen space!).
10419
ImVec2 ImGui::GetContentRegionMax()
10420
0
{
10421
0
    ImGuiContext& g = *GImGui;
10422
0
    ImGuiWindow* window = g.CurrentWindow;
10423
0
    ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
10424
0
    if (window->DC.CurrentColumns || g.CurrentTable)
10425
0
        mx.x = window->WorkRect.Max.x - window->Pos.x;
10426
0
    return mx;
10427
0
}
10428
10429
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10430
ImVec2 ImGui::GetContentRegionMaxAbs()
10431
9.51k
{
10432
9.51k
    ImGuiContext& g = *GImGui;
10433
9.51k
    ImGuiWindow* window = g.CurrentWindow;
10434
9.51k
    ImVec2 mx = window->ContentRegionRect.Max;
10435
9.51k
    if (window->DC.CurrentColumns || g.CurrentTable)
10436
0
        mx.x = window->WorkRect.Max.x;
10437
9.51k
    return mx;
10438
9.51k
}
10439
10440
ImVec2 ImGui::GetContentRegionAvail()
10441
9.51k
{
10442
9.51k
    ImGuiWindow* window = GImGui->CurrentWindow;
10443
9.51k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10444
9.51k
}
10445
10446
// In window space (not screen space!)
10447
ImVec2 ImGui::GetWindowContentRegionMin()
10448
0
{
10449
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10450
0
    return window->ContentRegionRect.Min - window->Pos;
10451
0
}
10452
10453
ImVec2 ImGui::GetWindowContentRegionMax()
10454
9.51k
{
10455
9.51k
    ImGuiWindow* window = GImGui->CurrentWindow;
10456
9.51k
    return window->ContentRegionRect.Max - window->Pos;
10457
9.51k
}
10458
10459
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10460
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10461
// FIXME-OPT: Could we safely early out on ->SkipItems?
10462
void ImGui::BeginGroup()
10463
0
{
10464
0
    ImGuiContext& g = *GImGui;
10465
0
    ImGuiWindow* window = g.CurrentWindow;
10466
10467
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10468
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10469
0
    group_data.WindowID = window->ID;
10470
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10471
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10472
0
    group_data.BackupIndent = window->DC.Indent;
10473
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10474
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10475
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10476
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10477
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10478
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10479
0
    group_data.EmitItem = true;
10480
10481
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10482
0
    window->DC.Indent = window->DC.GroupOffset;
10483
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10484
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10485
0
    if (g.LogEnabled)
10486
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10487
0
}
10488
10489
void ImGui::EndGroup()
10490
0
{
10491
0
    ImGuiContext& g = *GImGui;
10492
0
    ImGuiWindow* window = g.CurrentWindow;
10493
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10494
10495
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10496
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10497
10498
0
    if (window->DC.IsSetPos)
10499
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10500
10501
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10502
10503
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10504
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10505
0
    window->DC.Indent = group_data.BackupIndent;
10506
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10507
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10508
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10509
0
    if (g.LogEnabled)
10510
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10511
10512
0
    if (!group_data.EmitItem)
10513
0
    {
10514
0
        g.GroupStack.pop_back();
10515
0
        return;
10516
0
    }
10517
10518
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10519
0
    ItemSize(group_bb.GetSize());
10520
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10521
10522
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10523
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10524
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10525
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10526
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10527
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10528
0
    if (group_contains_curr_active_id)
10529
0
        g.LastItemData.ID = g.ActiveId;
10530
0
    else if (group_contains_prev_active_id)
10531
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10532
0
    g.LastItemData.Rect = group_bb;
10533
10534
    // Forward Hovered flag
10535
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10536
0
    if (group_contains_curr_hovered_id)
10537
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10538
10539
    // Forward Edited flag
10540
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10541
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10542
10543
    // Forward Deactivated flag
10544
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10545
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10546
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10547
10548
0
    g.GroupStack.pop_back();
10549
    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10550
0
}
10551
10552
10553
//-----------------------------------------------------------------------------
10554
// [SECTION] SCROLLING
10555
//-----------------------------------------------------------------------------
10556
10557
// Helper to snap on edges when aiming at an item very close to the edge,
10558
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10559
// When we refactor the scrolling API this may be configurable with a flag?
10560
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10561
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10562
0
{
10563
0
    if (target <= snap_min + snap_threshold)
10564
0
        return ImLerp(snap_min, target, center_ratio);
10565
0
    if (target >= snap_max - snap_threshold)
10566
0
        return ImLerp(target, snap_max, center_ratio);
10567
0
    return target;
10568
0
}
10569
10570
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10571
45.5k
{
10572
45.5k
    ImVec2 scroll = window->Scroll;
10573
45.5k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10574
136k
    for (int axis = 0; axis < 2; axis++)
10575
91.1k
    {
10576
91.1k
        if (window->ScrollTarget[axis] < FLT_MAX)
10577
11.4k
        {
10578
11.4k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10579
11.4k
            float scroll_target = window->ScrollTarget[axis];
10580
11.4k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10581
0
            {
10582
0
                float snap_min = 0.0f;
10583
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10584
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10585
0
            }
10586
11.4k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10587
11.4k
        }
10588
91.1k
        scroll[axis] = IM_FLOOR(ImMax(scroll[axis], 0.0f));
10589
91.1k
        if (!window->Collapsed && !window->SkipItems)
10590
72.1k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10591
91.1k
    }
10592
45.5k
    return scroll;
10593
45.5k
}
10594
10595
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10596
0
{
10597
0
    ImGuiContext& g = *GImGui;
10598
0
    ImGuiWindow* window = g.CurrentWindow;
10599
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10600
0
}
10601
10602
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10603
0
{
10604
0
    ScrollToRectEx(window, item_rect, flags);
10605
0
}
10606
10607
// Scroll to keep newly navigated item fully into view
10608
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10609
8
{
10610
8
    ImGuiContext& g = *GImGui;
10611
8
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10612
8
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10613
8
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10614
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10615
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10616
10617
    // Check that only one behavior is selected per axis
10618
8
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10619
8
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10620
10621
    // Defaults
10622
8
    ImGuiScrollFlags in_flags = flags;
10623
8
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10624
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10625
8
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10626
4
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10627
10628
8
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10629
8
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10630
8
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10631
8
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10632
10633
8
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10634
0
    {
10635
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10636
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10637
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10638
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10639
0
    }
10640
8
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10641
0
    {
10642
0
        if (can_be_fully_visible_x)
10643
0
            SetScrollFromPosX(window, ImFloor((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10644
0
        else
10645
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10646
0
    }
10647
10648
8
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10649
0
    {
10650
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10651
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10652
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10653
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10654
0
    }
10655
8
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10656
0
    {
10657
0
        if (can_be_fully_visible_y)
10658
0
            SetScrollFromPosY(window, ImFloor((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10659
0
        else
10660
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10661
0
    }
10662
10663
8
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10664
8
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10665
10666
    // Also scroll parent window to keep us into view if necessary
10667
8
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10668
0
    {
10669
        // FIXME-SCROLL: May be an option?
10670
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10671
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10672
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10673
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10674
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10675
0
    }
10676
10677
8
    return delta_scroll;
10678
8
}
10679
10680
float ImGui::GetScrollX()
10681
15.5k
{
10682
15.5k
    ImGuiWindow* window = GImGui->CurrentWindow;
10683
15.5k
    return window->Scroll.x;
10684
15.5k
}
10685
10686
float ImGui::GetScrollY()
10687
15.5k
{
10688
15.5k
    ImGuiWindow* window = GImGui->CurrentWindow;
10689
15.5k
    return window->Scroll.y;
10690
15.5k
}
10691
10692
float ImGui::GetScrollMaxX()
10693
0
{
10694
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10695
0
    return window->ScrollMax.x;
10696
0
}
10697
10698
float ImGui::GetScrollMaxY()
10699
0
{
10700
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10701
0
    return window->ScrollMax.y;
10702
0
}
10703
10704
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10705
5.97k
{
10706
5.97k
    window->ScrollTarget.x = scroll_x;
10707
5.97k
    window->ScrollTargetCenterRatio.x = 0.0f;
10708
5.97k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10709
5.97k
}
10710
10711
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10712
5.51k
{
10713
5.51k
    window->ScrollTarget.y = scroll_y;
10714
5.51k
    window->ScrollTargetCenterRatio.y = 0.0f;
10715
5.51k
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10716
5.51k
}
10717
10718
void ImGui::SetScrollX(float scroll_x)
10719
5.90k
{
10720
5.90k
    ImGuiContext& g = *GImGui;
10721
5.90k
    SetScrollX(g.CurrentWindow, scroll_x);
10722
5.90k
}
10723
10724
void ImGui::SetScrollY(float scroll_y)
10725
5.45k
{
10726
5.45k
    ImGuiContext& g = *GImGui;
10727
5.45k
    SetScrollY(g.CurrentWindow, scroll_y);
10728
5.45k
}
10729
10730
// Note that a local position will vary depending on initial scroll value,
10731
// This is a little bit confusing so bear with us:
10732
//  - local_pos = (absolution_pos - window->Pos)
10733
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10734
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10735
//  - They mostly exist because of legacy API.
10736
// Following the rules above, when trying to work with scrolling code, consider that:
10737
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10738
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10739
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10740
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10741
0
{
10742
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10743
0
    window->ScrollTarget.x = IM_FLOOR(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10744
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10745
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10746
0
}
10747
10748
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10749
0
{
10750
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10751
0
    window->ScrollTarget.y = IM_FLOOR(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10752
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10753
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10754
0
}
10755
10756
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10757
0
{
10758
0
    ImGuiContext& g = *GImGui;
10759
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10760
0
}
10761
10762
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10763
0
{
10764
0
    ImGuiContext& g = *GImGui;
10765
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10766
0
}
10767
10768
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10769
void ImGui::SetScrollHereX(float center_x_ratio)
10770
0
{
10771
0
    ImGuiContext& g = *GImGui;
10772
0
    ImGuiWindow* window = g.CurrentWindow;
10773
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10774
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10775
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10776
10777
    // Tweak: snap on edges when aiming at an item very close to the edge
10778
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10779
0
}
10780
10781
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10782
void ImGui::SetScrollHereY(float center_y_ratio)
10783
0
{
10784
0
    ImGuiContext& g = *GImGui;
10785
0
    ImGuiWindow* window = g.CurrentWindow;
10786
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10787
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10788
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10789
10790
    // Tweak: snap on edges when aiming at an item very close to the edge
10791
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10792
0
}
10793
10794
//-----------------------------------------------------------------------------
10795
// [SECTION] TOOLTIPS
10796
//-----------------------------------------------------------------------------
10797
10798
bool ImGui::BeginTooltip()
10799
0
{
10800
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10801
0
}
10802
10803
bool ImGui::BeginItemTooltip()
10804
0
{
10805
0
    if (!IsItemHovered(ImGuiHoveredFlags_ForTooltip))
10806
0
        return false;
10807
0
    return BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10808
0
}
10809
10810
bool ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10811
0
{
10812
0
    ImGuiContext& g = *GImGui;
10813
10814
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10815
0
    {
10816
        // Drag and Drop tooltips are positioning differently than other tooltips:
10817
        // - offset visibility to increase visibility around mouse.
10818
        // - never clamp within outer viewport boundary.
10819
        // We call SetNextWindowPos() to enforce position and disable clamping.
10820
        // See FindBestWindowPosForPopup() for positionning logic of other tooltips (not drag and drop ones).
10821
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10822
0
        ImVec2 tooltip_pos = g.IO.MousePos + TOOLTIP_DEFAULT_OFFSET * g.Style.MouseCursorScale;
10823
0
        SetNextWindowPos(tooltip_pos);
10824
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10825
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
10826
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePrevious;
10827
0
    }
10828
10829
0
    char window_name[16];
10830
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
10831
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePrevious)
10832
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
10833
0
            if (window->Active)
10834
0
            {
10835
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
10836
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(window);
10837
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
10838
0
            }
10839
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
10840
0
    Begin(window_name, NULL, flags | extra_window_flags);
10841
    // 2023-03-09: Added bool return value to the API, but currently always returning true.
10842
    // If this ever returns false we need to update BeginDragDropSource() accordingly.
10843
    //if (!ret)
10844
    //    End();
10845
    //return ret;
10846
0
    return true;
10847
0
}
10848
10849
void ImGui::EndTooltip()
10850
0
{
10851
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
10852
0
    End();
10853
0
}
10854
10855
void ImGui::SetTooltip(const char* fmt, ...)
10856
0
{
10857
0
    va_list args;
10858
0
    va_start(args, fmt);
10859
0
    SetTooltipV(fmt, args);
10860
0
    va_end(args);
10861
0
}
10862
10863
void ImGui::SetTooltipV(const char* fmt, va_list args)
10864
0
{
10865
0
    if (!BeginTooltipEx(ImGuiTooltipFlags_OverridePrevious, ImGuiWindowFlags_None))
10866
0
        return;
10867
0
    TextV(fmt, args);
10868
0
    EndTooltip();
10869
0
}
10870
10871
// Shortcut to use 'style.HoverFlagsForTooltipMouse' or 'style.HoverFlagsForTooltipNav'.
10872
// Defaults to == ImGuiHoveredFlags_Stationary | ImGuiHoveredFlags_DelayShort when using the mouse.
10873
void ImGui::SetItemTooltip(const char* fmt, ...)
10874
0
{
10875
0
    va_list args;
10876
0
    va_start(args, fmt);
10877
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
10878
0
        SetTooltipV(fmt, args);
10879
0
    va_end(args);
10880
0
}
10881
10882
void ImGui::SetItemTooltipV(const char* fmt, va_list args)
10883
0
{
10884
0
    if (IsItemHovered(ImGuiHoveredFlags_ForTooltip))
10885
0
        SetTooltipV(fmt, args);
10886
0
}
10887
10888
10889
//-----------------------------------------------------------------------------
10890
// [SECTION] POPUPS
10891
//-----------------------------------------------------------------------------
10892
10893
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
10894
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
10895
0
{
10896
0
    ImGuiContext& g = *GImGui;
10897
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
10898
0
    {
10899
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
10900
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
10901
0
        IM_ASSERT(id == 0);
10902
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10903
0
            return g.OpenPopupStack.Size > 0;
10904
0
        else
10905
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
10906
0
    }
10907
0
    else
10908
0
    {
10909
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10910
0
        {
10911
            // Return true if the popup is open anywhere in the popup stack
10912
0
            for (int n = 0; n < g.OpenPopupStack.Size; n++)
10913
0
                if (g.OpenPopupStack[n].PopupId == id)
10914
0
                    return true;
10915
0
            return false;
10916
0
        }
10917
0
        else
10918
0
        {
10919
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
10920
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
10921
0
        }
10922
0
    }
10923
0
}
10924
10925
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
10926
0
{
10927
0
    ImGuiContext& g = *GImGui;
10928
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
10929
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
10930
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
10931
0
    return IsPopupOpen(id, popup_flags);
10932
0
}
10933
10934
// Also see FindBlockingModal(NULL)
10935
ImGuiWindow* ImGui::GetTopMostPopupModal()
10936
54.1k
{
10937
54.1k
    ImGuiContext& g = *GImGui;
10938
54.1k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10939
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10940
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
10941
0
                return popup;
10942
54.1k
    return NULL;
10943
54.1k
}
10944
10945
// See Demo->Stacked Modal to confirm what this is for.
10946
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
10947
18.0k
{
10948
18.0k
    ImGuiContext& g = *GImGui;
10949
18.0k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10950
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10951
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
10952
0
                return popup;
10953
18.0k
    return NULL;
10954
18.0k
}
10955
10956
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
10957
0
{
10958
0
    ImGuiContext& g = *GImGui;
10959
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10960
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X)\n", str_id, id);
10961
0
    OpenPopupEx(id, popup_flags);
10962
0
}
10963
10964
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
10965
0
{
10966
0
    OpenPopupEx(id, popup_flags);
10967
0
}
10968
10969
// Mark popup as open (toggle toward open state).
10970
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
10971
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
10972
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
10973
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
10974
0
{
10975
0
    ImGuiContext& g = *GImGui;
10976
0
    ImGuiWindow* parent_window = g.CurrentWindow;
10977
0
    const int current_stack_size = g.BeginPopupStack.Size;
10978
10979
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
10980
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
10981
0
            return;
10982
10983
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
10984
0
    popup_ref.PopupId = id;
10985
0
    popup_ref.Window = NULL;
10986
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
10987
0
    popup_ref.OpenFrameCount = g.FrameCount;
10988
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
10989
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
10990
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
10991
10992
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
10993
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
10994
0
    {
10995
0
        g.OpenPopupStack.push_back(popup_ref);
10996
0
    }
10997
0
    else
10998
0
    {
10999
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
11000
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
11001
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
11002
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
11003
0
        {
11004
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
11005
0
        }
11006
0
        else
11007
0
        {
11008
            // Close child popups if any, then flag popup for open/reopen
11009
0
            ClosePopupToLevel(current_stack_size, false);
11010
0
            g.OpenPopupStack.push_back(popup_ref);
11011
0
        }
11012
11013
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
11014
        // This is equivalent to what ClosePopupToLevel() does.
11015
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
11016
        //    FocusWindow(parent_window);
11017
0
    }
11018
0
}
11019
11020
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
11021
// This function closes any popups that are over 'ref_window'.
11022
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
11023
4.91k
{
11024
4.91k
    ImGuiContext& g = *GImGui;
11025
4.91k
    if (g.OpenPopupStack.Size == 0)
11026
4.91k
        return;
11027
11028
    // Don't close our own child popup windows.
11029
0
    int popup_count_to_keep = 0;
11030
0
    if (ref_window)
11031
0
    {
11032
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
11033
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
11034
0
        {
11035
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
11036
0
            if (!popup.Window)
11037
0
                continue;
11038
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
11039
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
11040
0
                continue;
11041
11042
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
11043
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
11044
            //     Window -> Popup1 -> Popup2 -> Popup3
11045
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
11046
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
11047
0
            bool ref_window_is_descendent_of_popup = false;
11048
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
11049
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
11050
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
11051
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
11052
0
                    {
11053
0
                        ref_window_is_descendent_of_popup = true;
11054
0
                        break;
11055
0
                    }
11056
0
            if (!ref_window_is_descendent_of_popup)
11057
0
                break;
11058
0
        }
11059
0
    }
11060
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11061
0
    {
11062
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
11063
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
11064
0
    }
11065
0
}
11066
11067
void ImGui::ClosePopupsExceptModals()
11068
0
{
11069
0
    ImGuiContext& g = *GImGui;
11070
11071
0
    int popup_count_to_keep;
11072
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
11073
0
    {
11074
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
11075
0
        if (!window || (window->Flags & ImGuiWindowFlags_Modal))
11076
0
            break;
11077
0
    }
11078
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
11079
0
        ClosePopupToLevel(popup_count_to_keep, true);
11080
0
}
11081
11082
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
11083
0
{
11084
0
    ImGuiContext& g = *GImGui;
11085
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
11086
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
11087
11088
    // Trim open popup stack
11089
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
11090
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
11091
0
    g.OpenPopupStack.resize(remaining);
11092
11093
0
    if (restore_focus_to_window_under_popup)
11094
0
    {
11095
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
11096
0
        if (focus_window && !focus_window->WasActive && popup_window)
11097
0
            FocusTopMostWindowUnderOne(popup_window, NULL, NULL, ImGuiFocusRequestFlags_RestoreFocusedChild); // Fallback
11098
0
        else
11099
0
            FocusWindow(focus_window, (g.NavLayer == ImGuiNavLayer_Main) ? ImGuiFocusRequestFlags_RestoreFocusedChild : ImGuiFocusRequestFlags_None);
11100
0
    }
11101
0
}
11102
11103
// Close the popup we have begin-ed into.
11104
void ImGui::CloseCurrentPopup()
11105
0
{
11106
0
    ImGuiContext& g = *GImGui;
11107
0
    int popup_idx = g.BeginPopupStack.Size - 1;
11108
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
11109
0
        return;
11110
11111
    // Closing a menu closes its top-most parent popup (unless a modal)
11112
0
    while (popup_idx > 0)
11113
0
    {
11114
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
11115
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
11116
0
        bool close_parent = false;
11117
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
11118
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
11119
0
                close_parent = true;
11120
0
        if (!close_parent)
11121
0
            break;
11122
0
        popup_idx--;
11123
0
    }
11124
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
11125
0
    ClosePopupToLevel(popup_idx, true);
11126
11127
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
11128
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
11129
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
11130
0
    if (ImGuiWindow* window = g.NavWindow)
11131
0
        window->DC.NavHideHighlightOneFrame = true;
11132
0
}
11133
11134
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
11135
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
11136
0
{
11137
0
    ImGuiContext& g = *GImGui;
11138
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11139
0
    {
11140
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11141
0
        return false;
11142
0
    }
11143
11144
0
    char name[20];
11145
0
    if (flags & ImGuiWindowFlags_ChildMenu)
11146
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
11147
0
    else
11148
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
11149
11150
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
11151
0
    bool is_open = Begin(name, NULL, flags);
11152
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
11153
0
        EndPopup();
11154
11155
0
    return is_open;
11156
0
}
11157
11158
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
11159
0
{
11160
0
    ImGuiContext& g = *GImGui;
11161
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
11162
0
    {
11163
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11164
0
        return false;
11165
0
    }
11166
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
11167
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
11168
0
    return BeginPopupEx(id, flags);
11169
0
}
11170
11171
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
11172
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
11173
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
11174
0
{
11175
0
    ImGuiContext& g = *GImGui;
11176
0
    ImGuiWindow* window = g.CurrentWindow;
11177
0
    const ImGuiID id = window->GetID(name);
11178
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
11179
0
    {
11180
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
11181
0
        return false;
11182
0
    }
11183
11184
    // Center modal windows by default for increased visibility
11185
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
11186
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
11187
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
11188
0
    {
11189
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
11190
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
11191
0
    }
11192
11193
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
11194
0
    const bool is_open = Begin(name, p_open, flags);
11195
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
11196
0
    {
11197
0
        EndPopup();
11198
0
        if (is_open)
11199
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
11200
0
        return false;
11201
0
    }
11202
0
    return is_open;
11203
0
}
11204
11205
void ImGui::EndPopup()
11206
0
{
11207
0
    ImGuiContext& g = *GImGui;
11208
0
    ImGuiWindow* window = g.CurrentWindow;
11209
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
11210
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
11211
11212
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
11213
0
    if (g.NavWindow == window)
11214
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
11215
11216
    // Child-popups don't need to be laid out
11217
0
    IM_ASSERT(g.WithinEndChild == false);
11218
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
11219
0
        g.WithinEndChild = true;
11220
0
    End();
11221
0
    g.WithinEndChild = false;
11222
0
}
11223
11224
// Helper to open a popup if mouse button is released over the item
11225
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
11226
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
11227
0
{
11228
0
    ImGuiContext& g = *GImGui;
11229
0
    ImGuiWindow* window = g.CurrentWindow;
11230
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11231
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11232
0
    {
11233
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11234
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11235
0
        OpenPopupEx(id, popup_flags);
11236
0
    }
11237
0
}
11238
11239
// This is a helper to handle the simplest case of associating one named popup to one given widget.
11240
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
11241
// - To create a popup with a specific identifier, pass it in str_id.
11242
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
11243
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
11244
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
11245
//   This is essentially the same as:
11246
//       id = str_id ? GetID(str_id) : GetItemID();
11247
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
11248
//       return BeginPopup(id);
11249
//   Which is essentially the same as:
11250
//       id = str_id ? GetID(str_id) : GetItemID();
11251
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
11252
//           OpenPopup(id);
11253
//       return BeginPopup(id);
11254
//   The main difference being that this is tweaked to avoid computing the ID twice.
11255
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
11256
0
{
11257
0
    ImGuiContext& g = *GImGui;
11258
0
    ImGuiWindow* window = g.CurrentWindow;
11259
0
    if (window->SkipItems)
11260
0
        return false;
11261
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
11262
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
11263
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11264
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11265
0
        OpenPopupEx(id, popup_flags);
11266
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11267
0
}
11268
11269
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
11270
0
{
11271
0
    ImGuiContext& g = *GImGui;
11272
0
    ImGuiWindow* window = g.CurrentWindow;
11273
0
    if (!str_id)
11274
0
        str_id = "window_context";
11275
0
    ImGuiID id = window->GetID(str_id);
11276
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11277
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
11278
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
11279
0
            OpenPopupEx(id, popup_flags);
11280
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11281
0
}
11282
11283
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
11284
0
{
11285
0
    ImGuiContext& g = *GImGui;
11286
0
    ImGuiWindow* window = g.CurrentWindow;
11287
0
    if (!str_id)
11288
0
        str_id = "void_context";
11289
0
    ImGuiID id = window->GetID(str_id);
11290
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
11291
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
11292
0
        if (GetTopMostPopupModal() == NULL)
11293
0
            OpenPopupEx(id, popup_flags);
11294
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
11295
0
}
11296
11297
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
11298
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
11299
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
11300
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
11301
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
11302
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
11303
0
{
11304
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
11305
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
11306
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
11307
11308
    // Combo Box policy (we want a connecting edge)
11309
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
11310
0
    {
11311
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
11312
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11313
0
        {
11314
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11315
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11316
0
                continue;
11317
0
            ImVec2 pos;
11318
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11319
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11320
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11321
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11322
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11323
0
                continue;
11324
0
            *last_dir = dir;
11325
0
            return pos;
11326
0
        }
11327
0
    }
11328
11329
    // Tooltip and Default popup policy
11330
    // (Always first try the direction we used on the last frame, if any)
11331
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11332
0
    {
11333
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11334
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11335
0
        {
11336
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11337
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11338
0
                continue;
11339
11340
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11341
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11342
11343
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11344
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11345
0
                continue;
11346
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11347
0
                continue;
11348
11349
0
            ImVec2 pos;
11350
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11351
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11352
11353
            // Clamp top-left corner of popup
11354
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
11355
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
11356
11357
0
            *last_dir = dir;
11358
0
            return pos;
11359
0
        }
11360
0
    }
11361
11362
    // Fallback when not enough room:
11363
0
    *last_dir = ImGuiDir_None;
11364
11365
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11366
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11367
0
        return ref_pos + ImVec2(2, 2);
11368
11369
    // Otherwise try to keep within display
11370
0
    ImVec2 pos = ref_pos;
11371
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11372
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11373
0
    return pos;
11374
0
}
11375
11376
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11377
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11378
0
{
11379
0
    ImGuiContext& g = *GImGui;
11380
0
    ImRect r_screen;
11381
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11382
0
    {
11383
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11384
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11385
0
        r_screen.Min = monitor.WorkPos;
11386
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11387
0
    }
11388
0
    else
11389
0
    {
11390
        // Use the full viewport area (not work area) for popups
11391
0
        r_screen = window->Viewport->GetMainRect();
11392
0
    }
11393
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11394
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11395
0
    return r_screen;
11396
0
}
11397
11398
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11399
0
{
11400
0
    ImGuiContext& g = *GImGui;
11401
11402
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11403
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11404
0
    {
11405
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11406
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11407
0
        ImGuiWindow* parent_window = window->ParentWindow;
11408
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11409
0
        ImRect r_avoid;
11410
0
        if (parent_window->DC.MenuBarAppending)
11411
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11412
0
        else
11413
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11414
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11415
0
    }
11416
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11417
0
    {
11418
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11419
0
    }
11420
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11421
0
    {
11422
        // Position tooltip (always follows mouse + clamp within outer boundaries)
11423
        // Note that drag and drop tooltips are NOT using this path: BeginTooltipEx() manually sets their position.
11424
        // In theory we could handle both cases in same location, but requires a bit of shuffling as drag and drop tooltips are calling SetWindowPos() leading to 'window_pos_set_by_api' being set in Begin()
11425
0
        IM_ASSERT(g.CurrentWindow == window);
11426
0
        const float scale = g.Style.MouseCursorScale;
11427
0
        const ImVec2 ref_pos = NavCalcPreferredRefPos();
11428
0
        const ImVec2 tooltip_pos = ref_pos + TOOLTIP_DEFAULT_OFFSET * scale;
11429
0
        ImRect r_avoid;
11430
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11431
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11432
0
        else
11433
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * scale, ref_pos.y + 24 * scale); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11434
        //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255, 0, 255, 255));
11435
0
        return FindBestWindowPosForPopupEx(tooltip_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11436
0
    }
11437
0
    IM_ASSERT(0);
11438
0
    return window->Pos;
11439
0
}
11440
11441
//-----------------------------------------------------------------------------
11442
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11443
//-----------------------------------------------------------------------------
11444
11445
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11446
// In our terminology those should be interchangeable, yet right now this is super confusing.
11447
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11448
11449
void ImGui::SetNavWindow(ImGuiWindow* window)
11450
4.85k
{
11451
4.85k
    ImGuiContext& g = *GImGui;
11452
4.85k
    if (g.NavWindow != window)
11453
4.85k
    {
11454
4.85k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11455
4.85k
        g.NavWindow = window;
11456
4.85k
    }
11457
4.85k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11458
4.85k
    NavUpdateAnyRequestFlag();
11459
4.85k
}
11460
11461
void ImGui::NavClearPreferredPosForAxis(ImGuiAxis axis)
11462
377
{
11463
377
    ImGuiContext& g = *GImGui;
11464
377
    g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer][axis] = FLT_MAX;
11465
377
}
11466
11467
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11468
99
{
11469
99
    ImGuiContext& g = *GImGui;
11470
99
    IM_ASSERT(g.NavWindow != NULL);
11471
99
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11472
99
    g.NavId = id;
11473
99
    g.NavLayer = nav_layer;
11474
99
    g.NavFocusScopeId = focus_scope_id;
11475
99
    g.NavWindow->NavLastIds[nav_layer] = id;
11476
99
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11477
11478
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11479
99
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11480
99
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11481
99
}
11482
11483
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11484
44
{
11485
44
    ImGuiContext& g = *GImGui;
11486
44
    IM_ASSERT(id != 0);
11487
11488
44
    if (g.NavWindow != window)
11489
24
       SetNavWindow(window);
11490
11491
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11492
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11493
44
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11494
44
    g.NavId = id;
11495
44
    g.NavLayer = nav_layer;
11496
44
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11497
44
    window->NavLastIds[nav_layer] = id;
11498
44
    if (g.LastItemData.ID == id)
11499
44
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11500
11501
44
    if (g.ActiveIdSource == ImGuiInputSource_Keyboard || g.ActiveIdSource == ImGuiInputSource_Gamepad)
11502
0
        g.NavDisableMouseHover = true;
11503
44
    else
11504
44
        g.NavDisableHighlight = true;
11505
11506
    // Clear preferred scoring position (NavMoveRequestApplyResult() will tend to restore it)
11507
44
    NavClearPreferredPosForAxis(ImGuiAxis_X);
11508
44
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
11509
44
}
11510
11511
static ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11512
10
{
11513
10
    if (ImFabs(dx) > ImFabs(dy))
11514
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11515
10
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11516
10
}
11517
11518
static float inline NavScoreItemDistInterval(float cand_min, float cand_max, float curr_min, float curr_max)
11519
20
{
11520
20
    if (cand_max < curr_min)
11521
10
        return cand_max - curr_min;
11522
10
    if (curr_max < cand_min)
11523
0
        return cand_min - curr_max;
11524
10
    return 0.0f;
11525
10
}
11526
11527
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11528
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11529
24
{
11530
24
    ImGuiContext& g = *GImGui;
11531
24
    ImGuiWindow* window = g.CurrentWindow;
11532
24
    if (g.NavLayer != window->DC.NavLayerCurrent)
11533
14
        return false;
11534
11535
    // FIXME: Those are not good variables names
11536
10
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11537
10
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11538
10
    g.NavScoringDebugCount++;
11539
11540
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11541
10
    if (window->ParentWindow == g.NavWindow)
11542
0
    {
11543
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11544
0
        if (!window->ClipRect.Overlaps(cand))
11545
0
            return false;
11546
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11547
0
    }
11548
11549
    // Compute distance between boxes
11550
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11551
10
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11552
10
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11553
10
    if (dby != 0.0f && dbx != 0.0f)
11554
0
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11555
10
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11556
11557
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11558
10
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11559
10
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11560
10
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11561
11562
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11563
10
    ImGuiDir quadrant;
11564
10
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11565
10
    if (dbx != 0.0f || dby != 0.0f)
11566
10
    {
11567
        // For non-overlapping boxes, use distance between boxes
11568
10
        dax = dbx;
11569
10
        day = dby;
11570
10
        dist_axial = dist_box;
11571
10
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11572
10
    }
11573
0
    else if (dcx != 0.0f || dcy != 0.0f)
11574
0
    {
11575
        // For overlapping boxes with different centers, use distance between centers
11576
0
        dax = dcx;
11577
0
        day = dcy;
11578
0
        dist_axial = dist_center;
11579
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11580
0
    }
11581
0
    else
11582
0
    {
11583
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11584
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11585
0
    }
11586
11587
10
    const ImGuiDir move_dir = g.NavMoveDir;
11588
#if IMGUI_DEBUG_NAV_SCORING
11589
    char buf[200];
11590
    if (g.IO.KeyCtrl) // Hold CTRL to preview score in matching quadrant. CTRL+Arrow to rotate.
11591
    {
11592
        if (quadrant == move_dir)
11593
        {
11594
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11595
            ImDrawList* draw_list = GetForegroundDrawList(window);
11596
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 80));
11597
            draw_list->AddRectFilled(cand.Min, cand.Min + CalcTextSize(buf), IM_COL32(255, 0, 0, 200));
11598
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11599
        }
11600
    }
11601
    const bool debug_hovering = IsMouseHoveringRect(cand.Min, cand.Max);
11602
    const bool debug_tty = (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_Space));
11603
    if (debug_hovering || debug_tty)
11604
    {
11605
        ImFormatString(buf, IM_ARRAYSIZE(buf),
11606
            "d-box    (%7.3f,%7.3f) -> %7.3f\nd-center (%7.3f,%7.3f) -> %7.3f\nd-axial  (%7.3f,%7.3f) -> %7.3f\nnav %c, quadrant %c",
11607
            dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "-WENS"[move_dir+1], "-WENS"[quadrant+1]);
11608
        if (debug_hovering)
11609
        {
11610
            ImDrawList* draw_list = GetForegroundDrawList(window);
11611
            draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
11612
            draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255, 255, 0, 200));
11613
            draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40, 0, 0, 200));
11614
            draw_list->AddText(cand.Max, ~0U, buf);
11615
        }
11616
        if (debug_tty) { IMGUI_DEBUG_LOG_NAV("id 0x%08X\n%s\n", g.LastItemData.ID, buf); }
11617
    }
11618
#endif
11619
11620
    // Is it in the quadrant we're interested in moving to?
11621
10
    bool new_best = false;
11622
10
    if (quadrant == move_dir)
11623
10
    {
11624
        // Does it beat the current best candidate?
11625
10
        if (dist_box < result->DistBox)
11626
10
        {
11627
10
            result->DistBox = dist_box;
11628
10
            result->DistCenter = dist_center;
11629
10
            return true;
11630
10
        }
11631
0
        if (dist_box == result->DistBox)
11632
0
        {
11633
            // Try using distance between center points to break ties
11634
0
            if (dist_center < result->DistCenter)
11635
0
            {
11636
0
                result->DistCenter = dist_center;
11637
0
                new_best = true;
11638
0
            }
11639
0
            else if (dist_center == result->DistCenter)
11640
0
            {
11641
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11642
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11643
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11644
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11645
0
                    new_best = true;
11646
0
            }
11647
0
        }
11648
0
    }
11649
11650
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11651
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11652
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11653
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11654
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11655
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11656
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11657
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11658
0
            {
11659
0
                result->DistAxial = dist_axial;
11660
0
                new_best = true;
11661
0
            }
11662
11663
0
    return new_best;
11664
10
}
11665
11666
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11667
16
{
11668
16
    ImGuiContext& g = *GImGui;
11669
16
    ImGuiWindow* window = g.CurrentWindow;
11670
16
    result->Window = window;
11671
16
    result->ID = g.LastItemData.ID;
11672
16
    result->FocusScopeId = g.CurrentFocusScopeId;
11673
16
    result->InFlags = g.LastItemData.InFlags;
11674
16
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11675
16
}
11676
11677
// True when current work location may be scrolled horizontally when moving left / right.
11678
// This is generally always true UNLESS within a column. We don't have a vertical equivalent.
11679
void ImGui::NavUpdateCurrentWindowIsScrollPushableX()
11680
73.0k
{
11681
73.0k
    ImGuiContext& g = *GImGui;
11682
73.0k
    ImGuiWindow* window = g.CurrentWindow;
11683
73.0k
    window->DC.NavIsScrollPushableX = (g.CurrentTable == NULL && window->DC.CurrentColumns == NULL);
11684
73.0k
}
11685
11686
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11687
// This is called after LastItemData is set.
11688
static void ImGui::NavProcessItem()
11689
245
{
11690
245
    ImGuiContext& g = *GImGui;
11691
245
    ImGuiWindow* window = g.CurrentWindow;
11692
245
    const ImGuiID id = g.LastItemData.ID;
11693
245
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11694
11695
    // When inside a container that isn't scrollable with Left<>Right, clip NavRect accordingly (#2221)
11696
245
    if (window->DC.NavIsScrollPushableX == false)
11697
0
    {
11698
0
        g.LastItemData.NavRect.Min.x = ImClamp(g.LastItemData.NavRect.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11699
0
        g.LastItemData.NavRect.Max.x = ImClamp(g.LastItemData.NavRect.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
11700
0
    }
11701
245
    const ImRect nav_bb = g.LastItemData.NavRect;
11702
11703
    // Process Init Request
11704
245
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11705
1
    {
11706
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11707
1
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11708
1
        if (candidate_for_nav_default_focus || g.NavInitResult.ID == 0)
11709
1
        {
11710
1
            NavApplyItemToResult(&g.NavInitResult);
11711
1
        }
11712
1
        if (candidate_for_nav_default_focus)
11713
1
        {
11714
1
            g.NavInitRequest = false; // Found a match, clear request
11715
1
            NavUpdateAnyRequestFlag();
11716
1
        }
11717
1
    }
11718
11719
    // Process Move Request (scoring for navigation)
11720
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11721
245
    if (g.NavMoveScoringItems && (item_flags & ImGuiItemFlags_Disabled) == 0)
11722
26
    {
11723
26
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
11724
26
        if (is_tabbing)
11725
12
        {
11726
12
            NavProcessItemForTabbingRequest(id, item_flags, g.NavMoveFlags);
11727
12
        }
11728
14
        else if (g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId))
11729
13
        {
11730
13
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11731
13
            if (NavScoreItem(result))
11732
5
                NavApplyItemToResult(result);
11733
11734
            // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11735
13
            const float VISIBLE_RATIO = 0.70f;
11736
13
            if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11737
11
                if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11738
11
                    if (NavScoreItem(&g.NavMoveResultLocalVisible))
11739
5
                        NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11740
13
        }
11741
26
    }
11742
11743
    // Update information for currently focused/navigated item
11744
245
    if (g.NavId == id)
11745
227
    {
11746
227
        if (g.NavWindow != window)
11747
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11748
227
        g.NavLayer = window->DC.NavLayerCurrent;
11749
227
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11750
227
        g.NavIdIsAlive = true;
11751
227
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb); // Store item bounding box (relative to window position)
11752
227
    }
11753
245
}
11754
11755
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11756
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11757
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11758
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11759
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11760
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11761
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11762
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id, ImGuiItemFlags item_flags, ImGuiNavMoveFlags move_flags)
11763
12
{
11764
12
    ImGuiContext& g = *GImGui;
11765
11766
12
    if ((move_flags & ImGuiNavMoveFlags_FocusApi) == 0)
11767
12
        if (g.NavLayer != g.CurrentWindow->DC.NavLayerCurrent)
11768
7
            return;
11769
11770
    // - Can always land on an item when using API call.
11771
    // - Tabbing with _NavEnableKeyboard (space/enter/arrows): goes through every item.
11772
    // - Tabbing without _NavEnableKeyboard: goes through inputable items only.
11773
5
    bool can_stop;
11774
5
    if (move_flags & ImGuiNavMoveFlags_FocusApi)
11775
0
        can_stop = true;
11776
5
    else
11777
5
        can_stop = (item_flags & ImGuiItemFlags_NoTabStop) == 0 && ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) || (item_flags & ImGuiItemFlags_Inputable));
11778
11779
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11780
5
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11781
5
    if (g.NavTabbingDir == +1)
11782
5
    {
11783
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11784
5
        if (can_stop && g.NavTabbingResultFirst.ID == 0)
11785
5
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11786
5
        if (can_stop && g.NavTabbingCounter > 0 && --g.NavTabbingCounter == 0)
11787
0
            NavMoveRequestResolveWithLastItem(result);
11788
5
        else if (g.NavId == id)
11789
5
            g.NavTabbingCounter = 1;
11790
5
    }
11791
0
    else if (g.NavTabbingDir == -1)
11792
0
    {
11793
        // Tab Backward
11794
0
        if (g.NavId == id)
11795
0
        {
11796
0
            if (result->ID)
11797
0
            {
11798
0
                g.NavMoveScoringItems = false;
11799
0
                NavUpdateAnyRequestFlag();
11800
0
            }
11801
0
        }
11802
0
        else if (can_stop)
11803
0
        {
11804
            // Keep applying until reaching NavId
11805
0
            NavApplyItemToResult(result);
11806
0
        }
11807
0
    }
11808
0
    else if (g.NavTabbingDir == 0)
11809
0
    {
11810
0
        if (can_stop && g.NavId == id)
11811
0
            NavMoveRequestResolveWithLastItem(result);
11812
0
        if (can_stop && g.NavTabbingResultFirst.ID == 0) // Tab init
11813
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11814
0
    }
11815
5
}
11816
11817
bool ImGui::NavMoveRequestButNoResultYet()
11818
7.66k
{
11819
7.66k
    ImGuiContext& g = *GImGui;
11820
7.66k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
11821
7.66k
}
11822
11823
// FIXME: ScoringRect is not set
11824
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11825
135
{
11826
135
    ImGuiContext& g = *GImGui;
11827
135
    IM_ASSERT(g.NavWindow != NULL);
11828
11829
135
    if (move_flags & ImGuiNavMoveFlags_Tabbing)
11830
22
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
11831
11832
135
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
11833
135
    g.NavMoveDir = move_dir;
11834
135
    g.NavMoveDirForDebug = move_dir;
11835
135
    g.NavMoveClipDir = clip_dir;
11836
135
    g.NavMoveFlags = move_flags;
11837
135
    g.NavMoveScrollFlags = scroll_flags;
11838
135
    g.NavMoveForwardToNextFrame = false;
11839
135
    g.NavMoveKeyMods = g.IO.KeyMods;
11840
135
    g.NavMoveResultLocal.Clear();
11841
135
    g.NavMoveResultLocalVisible.Clear();
11842
135
    g.NavMoveResultOther.Clear();
11843
135
    g.NavTabbingCounter = 0;
11844
135
    g.NavTabbingResultFirst.Clear();
11845
135
    NavUpdateAnyRequestFlag();
11846
135
}
11847
11848
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
11849
0
{
11850
0
    ImGuiContext& g = *GImGui;
11851
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
11852
0
    NavApplyItemToResult(result);
11853
0
    NavUpdateAnyRequestFlag();
11854
0
}
11855
11856
void ImGui::NavMoveRequestCancel()
11857
17
{
11858
17
    ImGuiContext& g = *GImGui;
11859
17
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11860
17
    NavUpdateAnyRequestFlag();
11861
17
}
11862
11863
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
11864
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11865
0
{
11866
0
    ImGuiContext& g = *GImGui;
11867
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
11868
0
    NavMoveRequestCancel();
11869
0
    g.NavMoveForwardToNextFrame = true;
11870
0
    g.NavMoveDir = move_dir;
11871
0
    g.NavMoveClipDir = clip_dir;
11872
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
11873
0
    g.NavMoveScrollFlags = scroll_flags;
11874
0
}
11875
11876
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
11877
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
11878
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
11879
0
{
11880
0
    ImGuiContext& g = *GImGui;
11881
0
    IM_ASSERT((wrap_flags & ImGuiNavMoveFlags_WrapMask_ ) != 0 && (wrap_flags & ~ImGuiNavMoveFlags_WrapMask_) == 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
11882
11883
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it:
11884
    // as NavEndFrame() will do the same test. It will end up calling NavUpdateCreateWrappingRequest().
11885
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
11886
0
        g.NavMoveFlags = (g.NavMoveFlags & ~ImGuiNavMoveFlags_WrapMask_) | wrap_flags;
11887
0
}
11888
11889
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
11890
// This way we could find the last focused window among our children. It would be much less confusing this way?
11891
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
11892
5.29k
{
11893
5.29k
    ImGuiWindow* parent = nav_window;
11894
10.3k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
11895
5.04k
        parent = parent->ParentWindow;
11896
5.29k
    if (parent && parent != nav_window)
11897
5.04k
        parent->NavLastChildNavWindow = nav_window;
11898
5.29k
}
11899
11900
// Restore the last focused child.
11901
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
11902
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
11903
18
{
11904
18
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
11905
7
        return window->NavLastChildNavWindow;
11906
11
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
11907
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
11908
0
            return tab->Window;
11909
11
    return window;
11910
11
}
11911
11912
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
11913
17
{
11914
17
    ImGuiContext& g = *GImGui;
11915
17
    if (layer == ImGuiNavLayer_Main)
11916
17
    {
11917
17
        ImGuiWindow* prev_nav_window = g.NavWindow;
11918
17
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
11919
17
        if (prev_nav_window)
11920
17
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
11921
17
    }
11922
17
    ImGuiWindow* window = g.NavWindow;
11923
17
    if (window->NavLastIds[layer] != 0)
11924
10
    {
11925
10
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
11926
10
    }
11927
7
    else
11928
7
    {
11929
7
        g.NavLayer = layer;
11930
7
        NavInitWindow(window, true);
11931
7
    }
11932
17
}
11933
11934
void ImGui::NavRestoreHighlightAfterMove()
11935
68
{
11936
68
    ImGuiContext& g = *GImGui;
11937
68
    g.NavDisableHighlight = false;
11938
68
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
11939
68
}
11940
11941
static inline void ImGui::NavUpdateAnyRequestFlag()
11942
23.0k
{
11943
23.0k
    ImGuiContext& g = *GImGui;
11944
23.0k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
11945
23.0k
    if (g.NavAnyRequest)
11946
23.0k
        IM_ASSERT(g.NavWindow != NULL);
11947
23.0k
}
11948
11949
// This needs to be called before we submit any widget (aka in or before Begin)
11950
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
11951
22
{
11952
    // FIXME: ChildWindow test here is wrong for docking
11953
22
    ImGuiContext& g = *GImGui;
11954
22
    IM_ASSERT(window == g.NavWindow);
11955
11956
22
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
11957
0
    {
11958
0
        g.NavId = 0;
11959
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11960
0
        return;
11961
0
    }
11962
11963
22
    bool init_for_nav = false;
11964
22
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
11965
22
        init_for_nav = true;
11966
22
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
11967
22
    if (init_for_nav)
11968
22
    {
11969
22
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
11970
22
        g.NavInitRequest = true;
11971
22
        g.NavInitRequestFromMove = false;
11972
22
        g.NavInitResult.ID = 0;
11973
22
        NavUpdateAnyRequestFlag();
11974
22
    }
11975
0
    else
11976
0
    {
11977
0
        g.NavId = window->NavLastIds[0];
11978
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11979
0
    }
11980
22
}
11981
11982
static ImVec2 ImGui::NavCalcPreferredRefPos()
11983
0
{
11984
0
    ImGuiContext& g = *GImGui;
11985
0
    ImGuiWindow* window = g.NavWindow;
11986
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
11987
0
    {
11988
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
11989
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
11990
        // In theory we could move that +1.0f offset in OpenPopupEx()
11991
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
11992
0
        return ImVec2(p.x + 1.0f, p.y);
11993
0
    }
11994
0
    else
11995
0
    {
11996
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
11997
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
11998
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
11999
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
12000
0
        {
12001
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
12002
0
            rect_rel.Translate(window->Scroll - next_scroll);
12003
0
        }
12004
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
12005
0
        ImGuiViewport* viewport = window->Viewport;
12006
0
        return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
12007
0
    }
12008
0
}
12009
12010
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
12011
0
{
12012
0
    ImGuiContext& g = *GImGui;
12013
0
    float repeat_delay, repeat_rate;
12014
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
12015
12016
0
    ImGuiKey key_less, key_more;
12017
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
12018
0
    {
12019
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
12020
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
12021
0
    }
12022
0
    else
12023
0
    {
12024
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
12025
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
12026
0
    }
12027
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
12028
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
12029
0
        amount = 0.0f;
12030
0
    return amount;
12031
0
}
12032
12033
static void ImGui::NavUpdate()
12034
18.0k
{
12035
18.0k
    ImGuiContext& g = *GImGui;
12036
18.0k
    ImGuiIO& io = g.IO;
12037
12038
18.0k
    io.WantSetMousePos = false;
12039
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
12040
12041
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
12042
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
12043
18.0k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12044
18.0k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
12045
18.0k
    if (nav_gamepad_active)
12046
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
12047
0
            if (IsKeyDown(key))
12048
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
12049
18.0k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12050
18.0k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
12051
18.0k
    if (nav_keyboard_active)
12052
18.0k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
12053
126k
            if (IsKeyDown(key))
12054
5.13k
                g.NavInputSource = ImGuiInputSource_Keyboard;
12055
12056
    // Process navigation init request (select first/default focus)
12057
18.0k
    g.NavJustMovedToId = 0;
12058
18.0k
    if (g.NavInitResult.ID != 0)
12059
1
        NavInitRequestApplyResult();
12060
18.0k
    g.NavInitRequest = false;
12061
18.0k
    g.NavInitRequestFromMove = false;
12062
18.0k
    g.NavInitResult.ID = 0;
12063
12064
    // Process navigation move request
12065
18.0k
    if (g.NavMoveSubmitted)
12066
99
        NavMoveRequestApplyResult();
12067
18.0k
    g.NavTabbingCounter = 0;
12068
18.0k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
12069
12070
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
12071
18.0k
    bool set_mouse_pos = false;
12072
18.0k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
12073
38
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
12074
38
            set_mouse_pos = true;
12075
18.0k
    g.NavMousePosDirty = false;
12076
18.0k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
12077
12078
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
12079
18.0k
    if (g.NavWindow)
12080
5.29k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
12081
18.0k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
12082
47
        g.NavWindow->NavLastChildNavWindow = NULL;
12083
12084
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
12085
18.0k
    NavUpdateWindowing();
12086
12087
    // Set output flags for user application
12088
18.0k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
12089
18.0k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
12090
12091
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
12092
18.0k
    NavUpdateCancelRequest();
12093
12094
    // Process manual activation request
12095
18.0k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = 0;
12096
18.0k
    g.NavActivateFlags = ImGuiActivateFlags_None;
12097
18.0k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12098
174
    {
12099
174
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
12100
174
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
12101
174
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
12102
174
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
12103
174
        if (g.ActiveId == 0 && activate_pressed)
12104
13
        {
12105
13
            g.NavActivateId = g.NavId;
12106
13
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
12107
13
        }
12108
174
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
12109
10
        {
12110
10
            g.NavActivateId = g.NavId;
12111
10
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
12112
10
        }
12113
174
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_down || input_down))
12114
41
            g.NavActivateDownId = g.NavId;
12115
174
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && (activate_pressed || input_pressed))
12116
14
            g.NavActivatePressedId = g.NavId;
12117
174
    }
12118
18.0k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
12119
0
        g.NavDisableHighlight = true;
12120
18.0k
    if (g.NavActivateId != 0)
12121
18.0k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
12122
12123
    // Process programmatic activation request
12124
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
12125
18.0k
    if (g.NavNextActivateId != 0)
12126
0
    {
12127
0
        g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
12128
0
        g.NavActivateFlags = g.NavNextActivateFlags;
12129
0
    }
12130
18.0k
    g.NavNextActivateId = 0;
12131
12132
    // Process move requests
12133
18.0k
    NavUpdateCreateMoveRequest();
12134
18.0k
    if (g.NavMoveDir == ImGuiDir_None)
12135
17.9k
        NavUpdateCreateTabbingRequest();
12136
18.0k
    NavUpdateAnyRequestFlag();
12137
18.0k
    g.NavIdIsAlive = false;
12138
12139
    // Scrolling
12140
18.0k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
12141
5.29k
    {
12142
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
12143
5.29k
        ImGuiWindow* window = g.NavWindow;
12144
5.29k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
12145
5.29k
        const ImGuiDir move_dir = g.NavMoveDir;
12146
5.29k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY && move_dir != ImGuiDir_None)
12147
105
        {
12148
105
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
12149
55
                SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
12150
105
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
12151
50
                SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
12152
105
        }
12153
12154
        // *Normal* Manual scroll with LStick
12155
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
12156
5.29k
        if (nav_gamepad_active)
12157
0
        {
12158
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12159
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
12160
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
12161
0
                SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
12162
0
            if (scroll_dir.y != 0.0f)
12163
0
                SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
12164
0
        }
12165
5.29k
    }
12166
12167
    // Always prioritize mouse highlight if navigation is disabled
12168
18.0k
    if (!nav_keyboard_active && !nav_gamepad_active)
12169
0
    {
12170
0
        g.NavDisableHighlight = true;
12171
0
        g.NavDisableMouseHover = set_mouse_pos = false;
12172
0
    }
12173
12174
    // Update mouse position if requested
12175
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
12176
18.0k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
12177
0
    {
12178
0
        io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
12179
0
        io.WantSetMousePos = true;
12180
        //IMGUI_DEBUG_LOG_IO("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
12181
0
    }
12182
12183
    // [DEBUG]
12184
18.0k
    g.NavScoringDebugCount = 0;
12185
#if IMGUI_DEBUG_NAV_RECTS
12186
    if (ImGuiWindow* debug_window = g.NavWindow)
12187
    {
12188
        ImDrawList* draw_list = GetForegroundDrawList(debug_window);
12189
        int layer = g.NavLayer; /* for (int layer = 0; layer < 2; layer++)*/ { ImRect r = WindowRectRelToAbs(debug_window, debug_window->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 200, 0, 255)); }
12190
        //if (1) { ImU32 col = (!debug_window->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
12191
    }
12192
#endif
12193
18.0k
}
12194
12195
void ImGui::NavInitRequestApplyResult()
12196
1
{
12197
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
12198
1
    ImGuiContext& g = *GImGui;
12199
1
    if (!g.NavWindow)
12200
1
        return;
12201
12202
0
    ImGuiNavItemData* result = &g.NavInitResult;
12203
0
    if (g.NavId != result->ID)
12204
0
    {
12205
0
        g.NavJustMovedToId = result->ID;
12206
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12207
0
        g.NavJustMovedToKeyMods = 0;
12208
0
    }
12209
12210
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
12211
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
12212
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12213
0
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12214
0
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
12215
0
    if (g.NavInitRequestFromMove)
12216
0
        NavRestoreHighlightAfterMove();
12217
0
}
12218
12219
// Bias scoring rect ahead of scoring + update preferred pos (if missing) using source position
12220
static void NavBiasScoringRect(ImRect& r, ImVec2& preferred_pos_rel, ImGuiDir move_dir, ImGuiNavMoveFlags move_flags)
12221
113
{
12222
    // Bias initial rect
12223
113
    ImGuiContext& g = *GImGui;
12224
113
    const ImVec2 rel_to_abs_offset = g.NavWindow->DC.CursorStartPos;
12225
12226
    // Initialize bias on departure if we don't have any. So mouse-click + arrow will record bias.
12227
    // - We default to L/U bias, so moving down from a large source item into several columns will land on left-most column.
12228
    // - But each successful move sets new bias on one axis, only cleared when using mouse.
12229
113
    if ((move_flags & ImGuiNavMoveFlags_Forwarded) == 0)
12230
113
    {
12231
113
        if (preferred_pos_rel.x == FLT_MAX)
12232
66
            preferred_pos_rel.x = ImMin(r.Min.x + 1.0f, r.Max.x) - rel_to_abs_offset.x;
12233
113
        if (preferred_pos_rel.y == FLT_MAX)
12234
48
            preferred_pos_rel.y = r.GetCenter().y - rel_to_abs_offset.y;
12235
113
    }
12236
12237
    // Apply general bias on the other axis
12238
113
    if ((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) && preferred_pos_rel.x != FLT_MAX)
12239
57
        r.Min.x = r.Max.x = preferred_pos_rel.x + rel_to_abs_offset.x;
12240
56
    else if ((move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right) && preferred_pos_rel.y != FLT_MAX)
12241
56
        r.Min.y = r.Max.y = preferred_pos_rel.y + rel_to_abs_offset.y;
12242
113
}
12243
12244
void ImGui::NavUpdateCreateMoveRequest()
12245
18.0k
{
12246
18.0k
    ImGuiContext& g = *GImGui;
12247
18.0k
    ImGuiIO& io = g.IO;
12248
18.0k
    ImGuiWindow* window = g.NavWindow;
12249
18.0k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12250
18.0k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12251
12252
18.0k
    if (g.NavMoveForwardToNextFrame && window != NULL)
12253
0
    {
12254
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
12255
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
12256
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
12257
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
12258
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
12259
0
    }
12260
18.0k
    else
12261
18.0k
    {
12262
        // Initiate directional inputs request
12263
18.0k
        g.NavMoveDir = ImGuiDir_None;
12264
18.0k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
12265
18.0k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
12266
18.0k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
12267
5.29k
        {
12268
5.29k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
12269
5.29k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
12270
5.29k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
12271
5.29k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
12272
5.29k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
12273
5.29k
        }
12274
18.0k
        g.NavMoveClipDir = g.NavMoveDir;
12275
18.0k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
12276
18.0k
    }
12277
12278
    // Update PageUp/PageDown/Home/End scroll
12279
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
12280
18.0k
    float scoring_rect_offset_y = 0.0f;
12281
18.0k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
12282
5.18k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
12283
18.0k
    if (scoring_rect_offset_y != 0.0f)
12284
6
    {
12285
6
        g.NavScoringNoClipRect = window->InnerRect;
12286
6
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
12287
6
    }
12288
12289
    // [DEBUG] Always send a request when holding CTRL. Hold CTRL + Arrow change the direction.
12290
#if IMGUI_DEBUG_NAV_SCORING
12291
    //if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
12292
    //    g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
12293
    if (io.KeyCtrl)
12294
    {
12295
        if (g.NavMoveDir == ImGuiDir_None)
12296
            g.NavMoveDir = g.NavMoveDirForDebug;
12297
        g.NavMoveClipDir = g.NavMoveDir;
12298
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
12299
    }
12300
#endif
12301
12302
    // Submit
12303
18.0k
    g.NavMoveForwardToNextFrame = false;
12304
18.0k
    if (g.NavMoveDir != ImGuiDir_None)
12305
113
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
12306
12307
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
12308
18.0k
    if (g.NavMoveSubmitted && g.NavId == 0)
12309
105
    {
12310
105
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
12311
105
        g.NavInitRequest = g.NavInitRequestFromMove = true;
12312
105
        g.NavInitResult.ID = 0;
12313
105
        g.NavDisableHighlight = false;
12314
105
    }
12315
12316
    // When using gamepad, we project the reference nav bounding box into window visible area.
12317
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling,
12318
    // since with gamepad all movements are relative (can't focus a visible object like we can with the mouse).
12319
18.0k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
12320
0
    {
12321
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
12322
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
12323
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
12324
12325
        // Take account of changing scroll to handle triggering a new move request on a scrolling frame. (#6171)
12326
        // Otherwise 'inner_rect_rel' would be off on the move result frame.
12327
0
        inner_rect_rel.Translate(CalcNextScrollFromScrollTargetAndClamp(window) - window->Scroll);
12328
12329
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
12330
0
        {
12331
0
            IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
12332
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
12333
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
12334
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
12335
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
12336
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
12337
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
12338
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
12339
0
            g.NavId = 0;
12340
0
        }
12341
0
    }
12342
12343
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
12344
18.0k
    ImRect scoring_rect;
12345
18.0k
    if (window != NULL)
12346
5.29k
    {
12347
5.29k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
12348
5.29k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
12349
5.29k
        scoring_rect.TranslateY(scoring_rect_offset_y);
12350
5.29k
        if (g.NavMoveSubmitted)
12351
113
            NavBiasScoringRect(scoring_rect, window->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer], g.NavMoveDir, g.NavMoveFlags);
12352
5.29k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
12353
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
12354
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
12355
5.29k
    }
12356
18.0k
    g.NavScoringRect = scoring_rect;
12357
18.0k
    g.NavScoringNoClipRect.Add(scoring_rect);
12358
18.0k
}
12359
12360
void ImGui::NavUpdateCreateTabbingRequest()
12361
17.9k
{
12362
17.9k
    ImGuiContext& g = *GImGui;
12363
17.9k
    ImGuiWindow* window = g.NavWindow;
12364
17.9k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
12365
17.9k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
12366
12.7k
        return;
12367
12368
5.17k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
12369
5.17k
    if (!tab_pressed)
12370
5.15k
        return;
12371
12372
    // Initiate tabbing request
12373
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
12374
    // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
12375
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
12376
22
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12377
22
    if (nav_keyboard_active)
12378
22
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.NavDisableHighlight == true && g.ActiveId == 0) ? 0 : +1;
12379
0
    else
12380
0
        g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
12381
22
    ImGuiNavMoveFlags move_flags = ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_Activate;
12382
22
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
12383
22
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
12384
22
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, move_flags, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
12385
22
    g.NavTabbingCounter = -1;
12386
22
}
12387
12388
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
12389
void ImGui::NavMoveRequestApplyResult()
12390
99
{
12391
99
    ImGuiContext& g = *GImGui;
12392
#if IMGUI_DEBUG_NAV_SCORING
12393
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
12394
        return;
12395
#endif
12396
12397
    // Select which result to use
12398
99
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12399
12400
    // Tabbing forward wrap
12401
99
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && result == NULL)
12402
15
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12403
4
            result = &g.NavTabbingResultFirst;
12404
12405
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12406
99
    const ImGuiAxis axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12407
99
    if (result == NULL)
12408
91
    {
12409
91
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
12410
11
            g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12411
91
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12412
1
            NavRestoreHighlightAfterMove();
12413
91
        NavClearPreferredPosForAxis(axis); // On a failed move, clear preferred pos for this axis.
12414
91
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveSubmitted but not led to a result!\n");
12415
91
        return;
12416
91
    }
12417
12418
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12419
8
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12420
4
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12421
0
            result = &g.NavMoveResultLocalVisible;
12422
12423
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12424
8
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12425
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12426
0
            result = &g.NavMoveResultOther;
12427
8
    IM_ASSERT(g.NavWindow && result->Window);
12428
12429
    // Scroll to keep newly navigated item fully into view.
12430
8
    if (g.NavLayer == ImGuiNavLayer_Main)
12431
8
    {
12432
8
        ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12433
8
        ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12434
12435
8
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12436
0
        {
12437
            // FIXME: Should remove this? Or make more precise: use ScrollToRectEx() with edge?
12438
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12439
0
            SetScrollY(result->Window, scroll_target);
12440
0
        }
12441
8
    }
12442
12443
8
    if (g.NavWindow != result->Window)
12444
0
    {
12445
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12446
0
        g.NavWindow = result->Window;
12447
0
    }
12448
8
    if (g.ActiveId != result->ID)
12449
8
        ClearActiveID();
12450
8
    if (g.NavId != result->ID && (g.NavMoveFlags & ImGuiNavMoveFlags_NoSelect) == 0)
12451
0
    {
12452
        // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12453
0
        g.NavJustMovedToId = result->ID;
12454
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12455
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12456
0
    }
12457
12458
    // Apply new NavID/Focus
12459
8
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12460
8
    ImVec2 preferred_scoring_pos_rel = g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer];
12461
8
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12462
12463
    // Restore last preferred position for current axis
12464
    // (storing in RootWindowForNav-> as the info is desirable at the beginning of a Move Request. In theory all storage should use RootWindowForNav..)
12465
8
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) == 0)
12466
4
    {
12467
4
        preferred_scoring_pos_rel[axis] = result->RectRel.GetCenter()[axis];
12468
4
        g.NavWindow->RootWindowForNav->NavPreferredScoringPosRel[g.NavLayer] = preferred_scoring_pos_rel;
12469
4
    }
12470
12471
    // Tabbing: Activates Inputable, otherwise only Focus
12472
8
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable) == 0)
12473
4
        g.NavMoveFlags &= ~ImGuiNavMoveFlags_Activate;
12474
12475
    // Activate
12476
8
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12477
0
    {
12478
0
        g.NavNextActivateId = result->ID;
12479
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12480
0
        g.NavMoveFlags |= ImGuiNavMoveFlags_NoSetNavHighlight;
12481
0
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
12482
0
            g.NavNextActivateFlags |= ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12483
0
    }
12484
12485
    // Enable nav highlight
12486
8
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_NoSetNavHighlight) == 0)
12487
8
        NavRestoreHighlightAfterMove();
12488
8
}
12489
12490
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12491
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12492
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12493
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12494
static void ImGui::NavUpdateCancelRequest()
12495
18.0k
{
12496
18.0k
    ImGuiContext& g = *GImGui;
12497
18.0k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12498
18.0k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12499
18.0k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12500
17.8k
        return;
12501
12502
202
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12503
202
    if (g.ActiveId != 0)
12504
0
    {
12505
0
        ClearActiveID();
12506
0
    }
12507
202
    else if (g.NavLayer != ImGuiNavLayer_Main)
12508
0
    {
12509
        // Leave the "menu" layer
12510
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12511
0
        NavRestoreHighlightAfterMove();
12512
0
    }
12513
202
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12514
59
    {
12515
        // Exit child window
12516
59
        ImGuiWindow* child_window = g.NavWindow;
12517
59
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12518
59
        IM_ASSERT(child_window->ChildId != 0);
12519
59
        ImRect child_rect = child_window->Rect();
12520
59
        FocusWindow(parent_window);
12521
59
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12522
59
        NavRestoreHighlightAfterMove();
12523
59
    }
12524
143
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12525
0
    {
12526
        // Close open popup/menu
12527
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12528
0
    }
12529
143
    else
12530
143
    {
12531
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12532
143
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12533
1
            g.NavWindow->NavLastIds[0] = 0;
12534
143
        g.NavId = 0;
12535
143
    }
12536
202
}
12537
12538
// Handle PageUp/PageDown/Home/End keys
12539
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12540
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12541
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12542
static float ImGui::NavUpdatePageUpPageDown()
12543
5.18k
{
12544
5.18k
    ImGuiContext& g = *GImGui;
12545
5.18k
    ImGuiWindow* window = g.NavWindow;
12546
5.18k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12547
0
        return 0.0f;
12548
12549
5.18k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12550
5.18k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12551
5.18k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12552
5.18k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12553
5.18k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12554
4.98k
        return 0.0f;
12555
12556
194
    if (g.NavLayer != ImGuiNavLayer_Main)
12557
17
        NavRestoreLayer(ImGuiNavLayer_Main);
12558
12559
194
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavWindowHasScrollY)
12560
91
    {
12561
        // Fallback manual-scroll when window has no navigable item
12562
91
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12563
6
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12564
85
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12565
1
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12566
84
        else if (home_pressed)
12567
1
            SetScrollY(window, 0.0f);
12568
83
        else if (end_pressed)
12569
1
            SetScrollY(window, window->ScrollMax.y);
12570
91
    }
12571
103
    else
12572
103
    {
12573
103
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12574
103
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12575
103
        float nav_scoring_rect_offset_y = 0.0f;
12576
103
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12577
0
        {
12578
0
            nav_scoring_rect_offset_y = -page_offset_y;
12579
0
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12580
0
            g.NavMoveClipDir = ImGuiDir_Up;
12581
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12582
0
        }
12583
103
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12584
6
        {
12585
6
            nav_scoring_rect_offset_y = +page_offset_y;
12586
6
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12587
6
            g.NavMoveClipDir = ImGuiDir_Down;
12588
6
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12589
6
        }
12590
97
        else if (home_pressed)
12591
0
        {
12592
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12593
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12594
            // Preserve current horizontal position if we have any.
12595
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12596
0
            if (nav_rect_rel.IsInverted())
12597
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12598
0
            g.NavMoveDir = ImGuiDir_Down;
12599
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12600
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12601
0
        }
12602
97
        else if (end_pressed)
12603
0
        {
12604
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12605
0
            if (nav_rect_rel.IsInverted())
12606
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12607
0
            g.NavMoveDir = ImGuiDir_Up;
12608
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12609
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12610
0
        }
12611
103
        return nav_scoring_rect_offset_y;
12612
103
    }
12613
91
    return 0.0f;
12614
194
}
12615
12616
static void ImGui::NavEndFrame()
12617
18.0k
{
12618
18.0k
    ImGuiContext& g = *GImGui;
12619
12620
    // Show CTRL+TAB list window
12621
18.0k
    if (g.NavWindowingTarget != NULL)
12622
0
        NavUpdateWindowingOverlay();
12623
12624
    // Perform wrap-around in menus
12625
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12626
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12627
18.0k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & ImGuiNavMoveFlags_WrapMask_) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12628
0
        NavUpdateCreateWrappingRequest();
12629
18.0k
}
12630
12631
static void ImGui::NavUpdateCreateWrappingRequest()
12632
0
{
12633
0
    ImGuiContext& g = *GImGui;
12634
0
    ImGuiWindow* window = g.NavWindow;
12635
12636
0
    bool do_forward = false;
12637
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12638
0
    ImGuiDir clip_dir = g.NavMoveDir;
12639
12640
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12641
    //const ImGuiAxis move_axis = (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? ImGuiAxis_Y : ImGuiAxis_X;
12642
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12643
0
    {
12644
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12645
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12646
0
        {
12647
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12648
0
            clip_dir = ImGuiDir_Up;
12649
0
        }
12650
0
        do_forward = true;
12651
0
    }
12652
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12653
0
    {
12654
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12655
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12656
0
        {
12657
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12658
0
            clip_dir = ImGuiDir_Down;
12659
0
        }
12660
0
        do_forward = true;
12661
0
    }
12662
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12663
0
    {
12664
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12665
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12666
0
        {
12667
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12668
0
            clip_dir = ImGuiDir_Left;
12669
0
        }
12670
0
        do_forward = true;
12671
0
    }
12672
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12673
0
    {
12674
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12675
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12676
0
        {
12677
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12678
0
            clip_dir = ImGuiDir_Right;
12679
0
        }
12680
0
        do_forward = true;
12681
0
    }
12682
0
    if (!do_forward)
12683
0
        return;
12684
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12685
0
    NavClearPreferredPosForAxis(ImGuiAxis_X);
12686
0
    NavClearPreferredPosForAxis(ImGuiAxis_Y);
12687
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12688
0
}
12689
12690
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12691
0
{
12692
0
    ImGuiContext& g = *GImGui;
12693
0
    IM_UNUSED(g);
12694
0
    int order = window->FocusOrder;
12695
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12696
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12697
0
    return order;
12698
0
}
12699
12700
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12701
0
{
12702
0
    ImGuiContext& g = *GImGui;
12703
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12704
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12705
0
            return g.WindowsFocusOrder[i];
12706
0
    return NULL;
12707
0
}
12708
12709
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12710
0
{
12711
0
    ImGuiContext& g = *GImGui;
12712
0
    IM_ASSERT(g.NavWindowingTarget);
12713
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12714
0
        return;
12715
12716
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12717
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12718
0
    if (!window_target)
12719
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12720
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12721
0
    {
12722
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12723
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12724
0
    }
12725
0
    g.NavWindowingToggleLayer = false;
12726
0
}
12727
12728
// Windowing management mode
12729
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12730
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12731
static void ImGui::NavUpdateWindowing()
12732
18.0k
{
12733
18.0k
    ImGuiContext& g = *GImGui;
12734
18.0k
    ImGuiIO& io = g.IO;
12735
12736
18.0k
    ImGuiWindow* apply_focus_window = NULL;
12737
18.0k
    bool apply_toggle_layer = false;
12738
12739
18.0k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12740
18.0k
    bool allow_windowing = (modal_window == NULL); // FIXME: This prevent CTRL+TAB from being usable with windows that are inside the Begin-stack of that modal.
12741
18.0k
    if (!allow_windowing)
12742
0
        g.NavWindowingTarget = NULL;
12743
12744
    // Fade out
12745
18.0k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12746
0
    {
12747
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12748
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12749
0
            g.NavWindowingTargetAnim = NULL;
12750
0
    }
12751
12752
    // Start CTRL+Tab or Square+L/R window selection
12753
18.0k
    const ImGuiID owner_id = ImHashStr("###NavUpdateWindowing");
12754
18.0k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12755
18.0k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12756
18.0k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12757
18.0k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, owner_id, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12758
18.0k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12759
18.0k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12760
18.0k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12761
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12762
0
        {
12763
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12764
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12765
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12766
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12767
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12768
12769
            // Register ownership of our mods. Using ImGuiInputFlags_RouteGlobalHigh in the Shortcut() calls instead would probably be correct but may have more side-effects.
12770
0
            if (keyboard_next_window || keyboard_prev_window)
12771
0
                SetKeyOwnersForKeyChord((g.ConfigNavWindowingKeyNext | g.ConfigNavWindowingKeyPrev) & ImGuiMod_Mask_, owner_id);
12772
0
        }
12773
12774
    // Gamepad update
12775
18.0k
    g.NavWindowingTimer += io.DeltaTime;
12776
18.0k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12777
0
    {
12778
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12779
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12780
12781
        // Select window to focus
12782
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12783
0
        if (focus_change_dir != 0)
12784
0
        {
12785
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12786
0
            g.NavWindowingHighlightAlpha = 1.0f;
12787
0
        }
12788
12789
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12790
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12791
0
        {
12792
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12793
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
12794
0
                apply_toggle_layer = true;
12795
0
            else if (!g.NavWindowingToggleLayer)
12796
0
                apply_focus_window = g.NavWindowingTarget;
12797
0
            g.NavWindowingTarget = NULL;
12798
0
        }
12799
0
    }
12800
12801
    // Keyboard: Focus
12802
18.0k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
12803
0
    {
12804
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
12805
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
12806
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
12807
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
12808
0
        if (keyboard_next_window || keyboard_prev_window)
12809
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
12810
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
12811
0
            apply_focus_window = g.NavWindowingTarget;
12812
0
    }
12813
12814
    // Keyboard: Press and Release ALT to toggle menu layer
12815
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
12816
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
12817
18.0k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
12818
0
    {
12819
0
        g.NavWindowingToggleLayer = true;
12820
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
12821
0
    }
12822
18.0k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
12823
0
    {
12824
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
12825
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
12826
        // We cancel toggling nav layer if an owner has claimed the key.
12827
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
12828
0
            g.NavWindowingToggleLayer = false;
12829
12830
        // Apply layer toggle on release
12831
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
12832
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
12833
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
12834
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
12835
0
                    apply_toggle_layer = true;
12836
0
        if (!IsKeyDown(ImGuiMod_Alt))
12837
0
            g.NavWindowingToggleLayer = false;
12838
0
    }
12839
12840
    // Move window
12841
18.0k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
12842
0
    {
12843
0
        ImVec2 nav_move_dir;
12844
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
12845
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
12846
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
12847
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12848
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
12849
0
        {
12850
0
            const float NAV_MOVE_SPEED = 800.0f;
12851
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
12852
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
12853
0
            g.NavDisableMouseHover = true;
12854
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaPos);
12855
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
12856
0
            {
12857
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
12858
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
12859
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
12860
0
            }
12861
0
        }
12862
0
    }
12863
12864
    // Apply final focus
12865
18.0k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
12866
0
    {
12867
        // FIXME: Many actions here could be part of a higher-level/reused function. Why aren't they in FocusWindow()
12868
        // Investigate for each of them: ClearActiveID(), NavRestoreHighlightAfterMove(), NavRestoreLastChildNavWindow(), ClosePopupsOverWindow(), NavInitWindow()
12869
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
12870
0
        ClearActiveID();
12871
0
        NavRestoreHighlightAfterMove();
12872
0
        ClosePopupsOverWindow(apply_focus_window, false);
12873
0
        FocusWindow(apply_focus_window, ImGuiFocusRequestFlags_RestoreFocusedChild);
12874
0
        apply_focus_window = g.NavWindow;
12875
0
        if (apply_focus_window->NavLastIds[0] == 0)
12876
0
            NavInitWindow(apply_focus_window, false);
12877
12878
        // If the window has ONLY a menu layer (no main layer), select it directly
12879
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
12880
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
12881
        // the target window as already been previewed once.
12882
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
12883
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
12884
        // won't be valid.
12885
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
12886
0
            g.NavLayer = ImGuiNavLayer_Menu;
12887
12888
        // Request OS level focus
12889
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
12890
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
12891
0
    }
12892
18.0k
    if (apply_focus_window)
12893
0
        g.NavWindowingTarget = NULL;
12894
12895
    // Apply menu/layer toggle
12896
18.0k
    if (apply_toggle_layer && g.NavWindow)
12897
0
    {
12898
0
        ClearActiveID();
12899
12900
        // Move to parent menu if necessary
12901
0
        ImGuiWindow* new_nav_window = g.NavWindow;
12902
0
        while (new_nav_window->ParentWindow
12903
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
12904
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
12905
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12906
0
            new_nav_window = new_nav_window->ParentWindow;
12907
0
        if (new_nav_window != g.NavWindow)
12908
0
        {
12909
0
            ImGuiWindow* old_nav_window = g.NavWindow;
12910
0
            FocusWindow(new_nav_window);
12911
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
12912
0
        }
12913
12914
        // Toggle layer
12915
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
12916
0
        if (new_nav_layer != g.NavLayer)
12917
0
        {
12918
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
12919
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
12920
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
12921
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
12922
0
            NavRestoreLayer(new_nav_layer);
12923
0
            NavRestoreHighlightAfterMove();
12924
0
        }
12925
0
    }
12926
18.0k
}
12927
12928
// Window has already passed the IsWindowNavFocusable()
12929
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
12930
0
{
12931
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12932
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
12933
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
12934
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
12935
0
    if (window->DockNodeAsHost)
12936
0
        return "(Dock node)"; // Not normally shown to user.
12937
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
12938
0
}
12939
12940
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
12941
void ImGui::NavUpdateWindowingOverlay()
12942
0
{
12943
0
    ImGuiContext& g = *GImGui;
12944
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
12945
12946
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
12947
0
        return;
12948
12949
0
    if (g.NavWindowingListWindow == NULL)
12950
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
12951
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
12952
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
12953
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
12954
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
12955
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
12956
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
12957
0
    {
12958
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
12959
0
        IM_ASSERT(window != NULL); // Fix static analyzers
12960
0
        if (!IsWindowNavFocusable(window))
12961
0
            continue;
12962
0
        const char* label = window->Name;
12963
0
        if (label == FindRenderedTextEnd(label))
12964
0
            label = GetFallbackWindowNameForWindowingList(window);
12965
0
        Selectable(label, g.NavWindowingTarget == window);
12966
0
    }
12967
0
    End();
12968
0
    PopStyleVar();
12969
0
}
12970
12971
12972
//-----------------------------------------------------------------------------
12973
// [SECTION] DRAG AND DROP
12974
//-----------------------------------------------------------------------------
12975
12976
bool ImGui::IsDragDropActive()
12977
0
{
12978
0
    ImGuiContext& g = *GImGui;
12979
0
    return g.DragDropActive;
12980
0
}
12981
12982
void ImGui::ClearDragDrop()
12983
6
{
12984
6
    ImGuiContext& g = *GImGui;
12985
6
    g.DragDropActive = false;
12986
6
    g.DragDropPayload.Clear();
12987
6
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
12988
6
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
12989
6
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
12990
6
    g.DragDropAcceptFrameCount = -1;
12991
12992
6
    g.DragDropPayloadBufHeap.clear();
12993
6
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12994
6
}
12995
12996
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
12997
// If the item has an identifier:
12998
// - This assume/require the item to be activated (typically via ButtonBehavior).
12999
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
13000
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
13001
// If the item has no identifier:
13002
// - Currently always assume left mouse button.
13003
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
13004
5
{
13005
5
    ImGuiContext& g = *GImGui;
13006
5
    ImGuiWindow* window = g.CurrentWindow;
13007
13008
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
13009
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
13010
5
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
13011
13012
5
    bool source_drag_active = false;
13013
5
    ImGuiID source_id = 0;
13014
5
    ImGuiID source_parent_id = 0;
13015
5
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
13016
5
    {
13017
5
        source_id = g.LastItemData.ID;
13018
5
        if (source_id != 0)
13019
5
        {
13020
            // Common path: items with ID
13021
5
            if (g.ActiveId != source_id)
13022
0
                return false;
13023
5
            if (g.ActiveIdMouseButton != -1)
13024
0
                mouse_button = g.ActiveIdMouseButton;
13025
5
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13026
0
                return false;
13027
5
            g.ActiveIdAllowOverlap = false;
13028
5
        }
13029
0
        else
13030
0
        {
13031
            // Uncommon path: items without ID
13032
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
13033
0
                return false;
13034
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
13035
0
                return false;
13036
13037
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
13038
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
13039
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
13040
0
            {
13041
0
                IM_ASSERT(0);
13042
0
                return false;
13043
0
            }
13044
13045
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
13046
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
13047
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
13048
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
13049
            // Rely on keeping other window->LastItemXXX fields intact.
13050
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
13051
0
            KeepAliveID(source_id);
13052
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id, g.LastItemData.InFlags);
13053
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
13054
0
            {
13055
0
                SetActiveID(source_id, window);
13056
0
                FocusWindow(window);
13057
0
            }
13058
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
13059
0
                g.ActiveIdAllowOverlap = is_hovered;
13060
0
        }
13061
5
        if (g.ActiveId != source_id)
13062
0
            return false;
13063
5
        source_parent_id = window->IDStack.back();
13064
5
        source_drag_active = IsMouseDragging(mouse_button);
13065
13066
        // Disable navigation and key inputs while dragging + cancel existing request if any
13067
5
        SetActiveIdUsingAllKeyboardKeys();
13068
5
    }
13069
0
    else
13070
0
    {
13071
0
        window = NULL;
13072
0
        source_id = ImHashStr("#SourceExtern");
13073
0
        source_drag_active = true;
13074
0
    }
13075
13076
5
    if (source_drag_active)
13077
5
    {
13078
5
        if (!g.DragDropActive)
13079
3
        {
13080
3
            IM_ASSERT(source_id != 0);
13081
3
            ClearDragDrop();
13082
3
            ImGuiPayload& payload = g.DragDropPayload;
13083
3
            payload.SourceId = source_id;
13084
3
            payload.SourceParentId = source_parent_id;
13085
3
            g.DragDropActive = true;
13086
3
            g.DragDropSourceFlags = flags;
13087
3
            g.DragDropMouseButton = mouse_button;
13088
3
            if (payload.SourceId == g.ActiveId)
13089
3
                g.ActiveIdNoClearOnFocusLoss = true;
13090
3
        }
13091
5
        g.DragDropSourceFrameCount = g.FrameCount;
13092
5
        g.DragDropWithinSource = true;
13093
13094
5
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13095
0
        {
13096
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
13097
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
13098
0
            bool ret = BeginTooltip();
13099
0
            IM_ASSERT(ret); // FIXME-NEWBEGIN: If this ever becomes false, we need to Begin("##Hidden", NULL, ImGuiWindowFlags_NoSavedSettings) + SetWindowHiddendAndSkipItemsForCurrentFrame().
13100
0
            IM_UNUSED(ret);
13101
13102
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
13103
0
                SetWindowHiddendAndSkipItemsForCurrentFrame(g.CurrentWindow);
13104
0
        }
13105
13106
5
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
13107
5
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
13108
13109
5
        return true;
13110
5
    }
13111
0
    return false;
13112
5
}
13113
13114
void ImGui::EndDragDropSource()
13115
5
{
13116
5
    ImGuiContext& g = *GImGui;
13117
5
    IM_ASSERT(g.DragDropActive);
13118
5
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
13119
13120
5
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
13121
0
        EndTooltip();
13122
13123
    // Discard the drag if have not called SetDragDropPayload()
13124
5
    if (g.DragDropPayload.DataFrameCount == -1)
13125
0
        ClearDragDrop();
13126
5
    g.DragDropWithinSource = false;
13127
5
}
13128
13129
// Use 'cond' to choose to submit payload on drag start or every frame
13130
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
13131
5
{
13132
5
    ImGuiContext& g = *GImGui;
13133
5
    ImGuiPayload& payload = g.DragDropPayload;
13134
5
    if (cond == 0)
13135
5
        cond = ImGuiCond_Always;
13136
13137
5
    IM_ASSERT(type != NULL);
13138
5
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
13139
5
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
13140
5
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
13141
5
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
13142
13143
5
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
13144
5
    {
13145
        // Copy payload
13146
5
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
13147
5
        g.DragDropPayloadBufHeap.resize(0);
13148
5
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
13149
0
        {
13150
            // Store in heap
13151
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
13152
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
13153
0
            memcpy(payload.Data, data, data_size);
13154
0
        }
13155
5
        else if (data_size > 0)
13156
5
        {
13157
            // Store locally
13158
5
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
13159
5
            payload.Data = g.DragDropPayloadBufLocal;
13160
5
            memcpy(payload.Data, data, data_size);
13161
5
        }
13162
0
        else
13163
0
        {
13164
0
            payload.Data = NULL;
13165
0
        }
13166
5
        payload.DataSize = (int)data_size;
13167
5
    }
13168
5
    payload.DataFrameCount = g.FrameCount;
13169
13170
    // Return whether the payload has been accepted
13171
5
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
13172
5
}
13173
13174
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
13175
14
{
13176
14
    ImGuiContext& g = *GImGui;
13177
14
    if (!g.DragDropActive)
13178
0
        return false;
13179
13180
14
    ImGuiWindow* window = g.CurrentWindow;
13181
14
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13182
14
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
13183
14
        return false;
13184
0
    IM_ASSERT(id != 0);
13185
0
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
13186
0
        return false;
13187
0
    if (window->SkipItems)
13188
0
        return false;
13189
13190
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13191
0
    g.DragDropTargetRect = bb;
13192
0
    g.DragDropTargetId = id;
13193
0
    g.DragDropWithinTarget = true;
13194
0
    return true;
13195
0
}
13196
13197
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
13198
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
13199
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
13200
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
13201
bool ImGui::BeginDragDropTarget()
13202
0
{
13203
0
    ImGuiContext& g = *GImGui;
13204
0
    if (!g.DragDropActive)
13205
0
        return false;
13206
13207
0
    ImGuiWindow* window = g.CurrentWindow;
13208
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
13209
0
        return false;
13210
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
13211
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
13212
0
        return false;
13213
13214
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
13215
0
    ImGuiID id = g.LastItemData.ID;
13216
0
    if (id == 0)
13217
0
    {
13218
0
        id = window->GetIDFromRectangle(display_rect);
13219
0
        KeepAliveID(id);
13220
0
    }
13221
0
    if (g.DragDropPayload.SourceId == id)
13222
0
        return false;
13223
13224
0
    IM_ASSERT(g.DragDropWithinTarget == false);
13225
0
    g.DragDropTargetRect = display_rect;
13226
0
    g.DragDropTargetId = id;
13227
0
    g.DragDropWithinTarget = true;
13228
0
    return true;
13229
0
}
13230
13231
bool ImGui::IsDragDropPayloadBeingAccepted()
13232
12
{
13233
12
    ImGuiContext& g = *GImGui;
13234
12
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
13235
12
}
13236
13237
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
13238
0
{
13239
0
    ImGuiContext& g = *GImGui;
13240
0
    ImGuiWindow* window = g.CurrentWindow;
13241
0
    ImGuiPayload& payload = g.DragDropPayload;
13242
0
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
13243
0
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
13244
0
    if (type != NULL && !payload.IsDataType(type))
13245
0
        return NULL;
13246
13247
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
13248
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
13249
0
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
13250
0
    ImRect r = g.DragDropTargetRect;
13251
0
    float r_surface = r.GetWidth() * r.GetHeight();
13252
0
    if (r_surface > g.DragDropAcceptIdCurrRectSurface)
13253
0
        return NULL;
13254
13255
0
    g.DragDropAcceptFlags = flags;
13256
0
    g.DragDropAcceptIdCurr = g.DragDropTargetId;
13257
0
    g.DragDropAcceptIdCurrRectSurface = r_surface;
13258
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: accept\n", g.DragDropTargetId);
13259
13260
    // Render default drop visuals
13261
0
    payload.Preview = was_accepted_previously;
13262
0
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
13263
0
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
13264
0
        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13265
13266
0
    g.DragDropAcceptFrameCount = g.FrameCount;
13267
0
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting OS window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
13268
0
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
13269
0
        return NULL;
13270
13271
    //IMGUI_DEBUG_LOG("AcceptDragDropPayload(): %08X: return payload\n", g.DragDropTargetId);
13272
0
    return &payload;
13273
0
}
13274
13275
// FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
13276
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
13277
0
{
13278
0
    GetWindowDrawList()->AddRect(bb.Min - ImVec2(3.5f, 3.5f), bb.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
13279
0
}
13280
13281
const ImGuiPayload* ImGui::GetDragDropPayload()
13282
0
{
13283
0
    ImGuiContext& g = *GImGui;
13284
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
13285
0
}
13286
13287
void ImGui::EndDragDropTarget()
13288
0
{
13289
0
    ImGuiContext& g = *GImGui;
13290
0
    IM_ASSERT(g.DragDropActive);
13291
0
    IM_ASSERT(g.DragDropWithinTarget);
13292
0
    g.DragDropWithinTarget = false;
13293
13294
    // Clear drag and drop state payload right after delivery
13295
0
    if (g.DragDropPayload.Delivery)
13296
0
        ClearDragDrop();
13297
0
}
13298
13299
//-----------------------------------------------------------------------------
13300
// [SECTION] LOGGING/CAPTURING
13301
//-----------------------------------------------------------------------------
13302
// All text output from the interface can be captured into tty/file/clipboard.
13303
// By default, tree nodes are automatically opened during logging.
13304
//-----------------------------------------------------------------------------
13305
13306
// Pass text data straight to log (without being displayed)
13307
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
13308
0
{
13309
0
    if (g.LogFile)
13310
0
    {
13311
0
        g.LogBuffer.Buf.resize(0);
13312
0
        g.LogBuffer.appendfv(fmt, args);
13313
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
13314
0
    }
13315
0
    else
13316
0
    {
13317
0
        g.LogBuffer.appendfv(fmt, args);
13318
0
    }
13319
0
}
13320
13321
void ImGui::LogText(const char* fmt, ...)
13322
0
{
13323
0
    ImGuiContext& g = *GImGui;
13324
0
    if (!g.LogEnabled)
13325
0
        return;
13326
13327
0
    va_list args;
13328
0
    va_start(args, fmt);
13329
0
    LogTextV(g, fmt, args);
13330
0
    va_end(args);
13331
0
}
13332
13333
void ImGui::LogTextV(const char* fmt, va_list args)
13334
0
{
13335
0
    ImGuiContext& g = *GImGui;
13336
0
    if (!g.LogEnabled)
13337
0
        return;
13338
13339
0
    LogTextV(g, fmt, args);
13340
0
}
13341
13342
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
13343
// We split text into individual lines to add current tree level padding
13344
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
13345
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
13346
0
{
13347
0
    ImGuiContext& g = *GImGui;
13348
0
    ImGuiWindow* window = g.CurrentWindow;
13349
13350
0
    const char* prefix = g.LogNextPrefix;
13351
0
    const char* suffix = g.LogNextSuffix;
13352
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13353
13354
0
    if (!text_end)
13355
0
        text_end = FindRenderedTextEnd(text, text_end);
13356
13357
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
13358
0
    if (ref_pos)
13359
0
        g.LogLinePosY = ref_pos->y;
13360
0
    if (log_new_line)
13361
0
    {
13362
0
        LogText(IM_NEWLINE);
13363
0
        g.LogLineFirstItem = true;
13364
0
    }
13365
13366
0
    if (prefix)
13367
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
13368
13369
    // Re-adjust padding if we have popped out of our starting depth
13370
0
    if (g.LogDepthRef > window->DC.TreeDepth)
13371
0
        g.LogDepthRef = window->DC.TreeDepth;
13372
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
13373
13374
0
    const char* text_remaining = text;
13375
0
    for (;;)
13376
0
    {
13377
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
13378
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
13379
0
        const char* line_start = text_remaining;
13380
0
        const char* line_end = ImStreolRange(line_start, text_end);
13381
0
        const bool is_last_line = (line_end == text_end);
13382
0
        if (line_start != line_end || !is_last_line)
13383
0
        {
13384
0
            const int line_length = (int)(line_end - line_start);
13385
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
13386
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
13387
0
            g.LogLineFirstItem = false;
13388
0
            if (*line_end == '\n')
13389
0
            {
13390
0
                LogText(IM_NEWLINE);
13391
0
                g.LogLineFirstItem = true;
13392
0
            }
13393
0
        }
13394
0
        if (is_last_line)
13395
0
            break;
13396
0
        text_remaining = line_end + 1;
13397
0
    }
13398
13399
0
    if (suffix)
13400
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
13401
0
}
13402
13403
// Start logging/capturing text output
13404
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
13405
0
{
13406
0
    ImGuiContext& g = *GImGui;
13407
0
    ImGuiWindow* window = g.CurrentWindow;
13408
0
    IM_ASSERT(g.LogEnabled == false);
13409
0
    IM_ASSERT(g.LogFile == NULL);
13410
0
    IM_ASSERT(g.LogBuffer.empty());
13411
0
    g.LogEnabled = true;
13412
0
    g.LogType = type;
13413
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
13414
0
    g.LogDepthRef = window->DC.TreeDepth;
13415
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
13416
0
    g.LogLinePosY = FLT_MAX;
13417
0
    g.LogLineFirstItem = true;
13418
0
}
13419
13420
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13421
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13422
0
{
13423
0
    ImGuiContext& g = *GImGui;
13424
0
    g.LogNextPrefix = prefix;
13425
0
    g.LogNextSuffix = suffix;
13426
0
}
13427
13428
void ImGui::LogToTTY(int auto_open_depth)
13429
0
{
13430
0
    ImGuiContext& g = *GImGui;
13431
0
    if (g.LogEnabled)
13432
0
        return;
13433
0
    IM_UNUSED(auto_open_depth);
13434
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13435
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13436
0
    g.LogFile = stdout;
13437
0
#endif
13438
0
}
13439
13440
// Start logging/capturing text output to given file
13441
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13442
0
{
13443
0
    ImGuiContext& g = *GImGui;
13444
0
    if (g.LogEnabled)
13445
0
        return;
13446
13447
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13448
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13449
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13450
0
    if (!filename)
13451
0
        filename = g.IO.LogFilename;
13452
0
    if (!filename || !filename[0])
13453
0
        return;
13454
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13455
0
    if (!f)
13456
0
    {
13457
0
        IM_ASSERT(0);
13458
0
        return;
13459
0
    }
13460
13461
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13462
0
    g.LogFile = f;
13463
0
}
13464
13465
// Start logging/capturing text output to clipboard
13466
void ImGui::LogToClipboard(int auto_open_depth)
13467
0
{
13468
0
    ImGuiContext& g = *GImGui;
13469
0
    if (g.LogEnabled)
13470
0
        return;
13471
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13472
0
}
13473
13474
void ImGui::LogToBuffer(int auto_open_depth)
13475
0
{
13476
0
    ImGuiContext& g = *GImGui;
13477
0
    if (g.LogEnabled)
13478
0
        return;
13479
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13480
0
}
13481
13482
void ImGui::LogFinish()
13483
36.0k
{
13484
36.0k
    ImGuiContext& g = *GImGui;
13485
36.0k
    if (!g.LogEnabled)
13486
36.0k
        return;
13487
13488
0
    LogText(IM_NEWLINE);
13489
0
    switch (g.LogType)
13490
0
    {
13491
0
    case ImGuiLogType_TTY:
13492
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13493
0
        fflush(g.LogFile);
13494
0
#endif
13495
0
        break;
13496
0
    case ImGuiLogType_File:
13497
0
        ImFileClose(g.LogFile);
13498
0
        break;
13499
0
    case ImGuiLogType_Buffer:
13500
0
        break;
13501
0
    case ImGuiLogType_Clipboard:
13502
0
        if (!g.LogBuffer.empty())
13503
0
            SetClipboardText(g.LogBuffer.begin());
13504
0
        break;
13505
0
    case ImGuiLogType_None:
13506
0
        IM_ASSERT(0);
13507
0
        break;
13508
0
    }
13509
13510
0
    g.LogEnabled = false;
13511
0
    g.LogType = ImGuiLogType_None;
13512
0
    g.LogFile = NULL;
13513
0
    g.LogBuffer.clear();
13514
0
}
13515
13516
// Helper to display logging buttons
13517
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13518
void ImGui::LogButtons()
13519
0
{
13520
0
    ImGuiContext& g = *GImGui;
13521
13522
0
    PushID("LogButtons");
13523
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13524
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13525
#else
13526
    const bool log_to_tty = false;
13527
#endif
13528
0
    const bool log_to_file = Button("Log To File"); SameLine();
13529
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13530
0
    PushTabStop(false);
13531
0
    SetNextItemWidth(80.0f);
13532
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13533
0
    PopTabStop();
13534
0
    PopID();
13535
13536
    // Start logging at the end of the function so that the buttons don't appear in the log
13537
0
    if (log_to_tty)
13538
0
        LogToTTY();
13539
0
    if (log_to_file)
13540
0
        LogToFile();
13541
0
    if (log_to_clipboard)
13542
0
        LogToClipboard();
13543
0
}
13544
13545
13546
//-----------------------------------------------------------------------------
13547
// [SECTION] SETTINGS
13548
//-----------------------------------------------------------------------------
13549
// - UpdateSettings() [Internal]
13550
// - MarkIniSettingsDirty() [Internal]
13551
// - FindSettingsHandler() [Internal]
13552
// - ClearIniSettings() [Internal]
13553
// - LoadIniSettingsFromDisk()
13554
// - LoadIniSettingsFromMemory()
13555
// - SaveIniSettingsToDisk()
13556
// - SaveIniSettingsToMemory()
13557
//-----------------------------------------------------------------------------
13558
// - CreateNewWindowSettings() [Internal]
13559
// - FindWindowSettingsByID() [Internal]
13560
// - FindWindowSettingsByWindow() [Internal]
13561
// - ClearWindowSettings() [Internal]
13562
// - WindowSettingsHandler_***() [Internal]
13563
//-----------------------------------------------------------------------------
13564
13565
// Called by NewFrame()
13566
void ImGui::UpdateSettings()
13567
18.0k
{
13568
    // Load settings on first frame (if not explicitly loaded manually before)
13569
18.0k
    ImGuiContext& g = *GImGui;
13570
18.0k
    if (!g.SettingsLoaded)
13571
1
    {
13572
1
        IM_ASSERT(g.SettingsWindows.empty());
13573
1
        if (g.IO.IniFilename)
13574
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13575
1
        g.SettingsLoaded = true;
13576
1
    }
13577
13578
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13579
18.0k
    if (g.SettingsDirtyTimer > 0.0f)
13580
1.80k
    {
13581
1.80k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13582
1.80k
        if (g.SettingsDirtyTimer <= 0.0f)
13583
6
        {
13584
6
            if (g.IO.IniFilename != NULL)
13585
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13586
6
            else
13587
6
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13588
6
            g.SettingsDirtyTimer = 0.0f;
13589
6
        }
13590
1.80k
    }
13591
18.0k
}
13592
13593
void ImGui::MarkIniSettingsDirty()
13594
0
{
13595
0
    ImGuiContext& g = *GImGui;
13596
0
    if (g.SettingsDirtyTimer <= 0.0f)
13597
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13598
0
}
13599
13600
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13601
1.92k
{
13602
1.92k
    ImGuiContext& g = *GImGui;
13603
1.92k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13604
30
        if (g.SettingsDirtyTimer <= 0.0f)
13605
6
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13606
1.92k
}
13607
13608
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13609
2
{
13610
2
    ImGuiContext& g = *GImGui;
13611
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13612
2
    g.SettingsHandlers.push_back(*handler);
13613
2
}
13614
13615
void ImGui::RemoveSettingsHandler(const char* type_name)
13616
0
{
13617
0
    ImGuiContext& g = *GImGui;
13618
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13619
0
        g.SettingsHandlers.erase(handler);
13620
0
}
13621
13622
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13623
2
{
13624
2
    ImGuiContext& g = *GImGui;
13625
2
    const ImGuiID type_hash = ImHashStr(type_name);
13626
3
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13627
1
        if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
13628
0
            return &g.SettingsHandlers[handler_n];
13629
2
    return NULL;
13630
2
}
13631
13632
// Clear all settings (windows, tables, docking etc.)
13633
void ImGui::ClearIniSettings()
13634
0
{
13635
0
    ImGuiContext& g = *GImGui;
13636
0
    g.SettingsIniData.clear();
13637
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13638
0
        if (g.SettingsHandlers[handler_n].ClearAllFn)
13639
0
            g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
13640
0
}
13641
13642
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13643
0
{
13644
0
    size_t file_data_size = 0;
13645
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13646
0
    if (!file_data)
13647
0
        return;
13648
0
    if (file_data_size > 0)
13649
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13650
0
    IM_FREE(file_data);
13651
0
}
13652
13653
// Zero-tolerance, no error reporting, cheap .ini parsing
13654
// Set ini_size==0 to let us use strlen(ini_data). Do not call this function with a 0 if your buffer is actually empty!
13655
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13656
0
{
13657
0
    ImGuiContext& g = *GImGui;
13658
0
    IM_ASSERT(g.Initialized);
13659
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13660
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13661
13662
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13663
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13664
0
    if (ini_size == 0)
13665
0
        ini_size = strlen(ini_data);
13666
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13667
0
    char* const buf = g.SettingsIniData.Buf.Data;
13668
0
    char* const buf_end = buf + ini_size;
13669
0
    memcpy(buf, ini_data, ini_size);
13670
0
    buf_end[0] = 0;
13671
13672
    // Call pre-read handlers
13673
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13674
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13675
0
        if (g.SettingsHandlers[handler_n].ReadInitFn)
13676
0
            g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
13677
13678
0
    void* entry_data = NULL;
13679
0
    ImGuiSettingsHandler* entry_handler = NULL;
13680
13681
0
    char* line_end = NULL;
13682
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13683
0
    {
13684
        // Skip new lines markers, then find end of the line
13685
0
        while (*line == '\n' || *line == '\r')
13686
0
            line++;
13687
0
        line_end = line;
13688
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13689
0
            line_end++;
13690
0
        line_end[0] = 0;
13691
0
        if (line[0] == ';')
13692
0
            continue;
13693
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13694
0
        {
13695
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13696
0
            line_end[-1] = 0;
13697
0
            const char* name_end = line_end - 1;
13698
0
            const char* type_start = line + 1;
13699
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13700
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13701
0
            if (!type_end || !name_start)
13702
0
                continue;
13703
0
            *type_end = 0; // Overwrite first ']'
13704
0
            name_start++;  // Skip second '['
13705
0
            entry_handler = FindSettingsHandler(type_start);
13706
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13707
0
        }
13708
0
        else if (entry_handler != NULL && entry_data != NULL)
13709
0
        {
13710
            // Let type handler parse the line
13711
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13712
0
        }
13713
0
    }
13714
0
    g.SettingsLoaded = true;
13715
13716
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13717
0
    memcpy(buf, ini_data, ini_size);
13718
13719
    // Call post-read handlers
13720
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13721
0
        if (g.SettingsHandlers[handler_n].ApplyAllFn)
13722
0
            g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
13723
0
}
13724
13725
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13726
0
{
13727
0
    ImGuiContext& g = *GImGui;
13728
0
    g.SettingsDirtyTimer = 0.0f;
13729
0
    if (!ini_filename)
13730
0
        return;
13731
13732
0
    size_t ini_data_size = 0;
13733
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13734
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13735
0
    if (!f)
13736
0
        return;
13737
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13738
0
    ImFileClose(f);
13739
0
}
13740
13741
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13742
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13743
0
{
13744
0
    ImGuiContext& g = *GImGui;
13745
0
    g.SettingsDirtyTimer = 0.0f;
13746
0
    g.SettingsIniData.Buf.resize(0);
13747
0
    g.SettingsIniData.Buf.push_back(0);
13748
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13749
0
    {
13750
0
        ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
13751
0
        handler->WriteAllFn(&g, handler, &g.SettingsIniData);
13752
0
    }
13753
0
    if (out_size)
13754
0
        *out_size = (size_t)g.SettingsIniData.size();
13755
0
    return g.SettingsIniData.c_str();
13756
0
}
13757
13758
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13759
0
{
13760
0
    ImGuiContext& g = *GImGui;
13761
13762
0
    if (g.IO.ConfigDebugIniSettings == false)
13763
0
    {
13764
        // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13765
        // Preserve the full string when ConfigDebugVerboseIniSettings is set to make .ini inspection easier.
13766
0
        if (const char* p = strstr(name, "###"))
13767
0
            name = p;
13768
0
    }
13769
0
    const size_t name_len = strlen(name);
13770
13771
    // Allocate chunk
13772
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13773
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13774
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13775
0
    settings->ID = ImHashStr(name, name_len);
13776
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13777
13778
0
    return settings;
13779
0
}
13780
13781
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
13782
// This is called once per window .ini entry + once per newly instantiated window.
13783
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
13784
2
{
13785
2
    ImGuiContext& g = *GImGui;
13786
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13787
0
        if (settings->ID == id && !settings->WantDelete)
13788
0
            return settings;
13789
2
    return NULL;
13790
2
}
13791
13792
// This is faster if you are holding on a Window already as we don't need to perform a search.
13793
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
13794
2
{
13795
2
    ImGuiContext& g = *GImGui;
13796
2
    if (window->SettingsOffset != -1)
13797
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
13798
2
    return FindWindowSettingsByID(window->ID);
13799
2
}
13800
13801
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
13802
void ImGui::ClearWindowSettings(const char* name)
13803
0
{
13804
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
13805
0
    ImGuiContext& g = *GImGui;
13806
0
    ImGuiWindow* window = FindWindowByName(name);
13807
0
    if (window != NULL)
13808
0
    {
13809
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
13810
0
        InitOrLoadWindowSettings(window, NULL);
13811
0
        if (window->DockId != 0)
13812
0
            DockContextProcessUndockWindow(&g, window, true);
13813
0
    }
13814
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
13815
0
        settings->WantDelete = true;
13816
0
}
13817
13818
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13819
0
{
13820
0
    ImGuiContext& g = *ctx;
13821
0
    for (int i = 0; i != g.Windows.Size; i++)
13822
0
        g.Windows[i]->SettingsOffset = -1;
13823
0
    g.SettingsWindows.clear();
13824
0
}
13825
13826
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
13827
0
{
13828
0
    ImGuiID id = ImHashStr(name);
13829
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
13830
0
    if (settings)
13831
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
13832
0
    else
13833
0
        settings = ImGui::CreateNewWindowSettings(name);
13834
0
    settings->ID = id;
13835
0
    settings->WantApply = true;
13836
0
    return (void*)settings;
13837
0
}
13838
13839
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
13840
0
{
13841
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
13842
0
    int x, y;
13843
0
    int i;
13844
0
    ImU32 u1;
13845
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
13846
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
13847
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
13848
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
13849
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
13850
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
13851
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
13852
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
13853
0
}
13854
13855
// Apply to existing windows (if any)
13856
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13857
0
{
13858
0
    ImGuiContext& g = *ctx;
13859
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13860
0
        if (settings->WantApply)
13861
0
        {
13862
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
13863
0
                ApplyWindowSettings(window, settings);
13864
0
            settings->WantApply = false;
13865
0
        }
13866
0
}
13867
13868
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
13869
0
{
13870
    // Gather data from windows that were active during this session
13871
    // (if a window wasn't opened in this session we preserve its settings)
13872
0
    ImGuiContext& g = *ctx;
13873
0
    for (int i = 0; i != g.Windows.Size; i++)
13874
0
    {
13875
0
        ImGuiWindow* window = g.Windows[i];
13876
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
13877
0
            continue;
13878
13879
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
13880
0
        if (!settings)
13881
0
        {
13882
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
13883
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
13884
0
        }
13885
0
        IM_ASSERT(settings->ID == window->ID);
13886
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
13887
0
        settings->Size = ImVec2ih(window->SizeFull);
13888
0
        settings->ViewportId = window->ViewportId;
13889
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
13890
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
13891
0
        settings->DockId = window->DockId;
13892
0
        settings->ClassId = window->WindowClass.ClassId;
13893
0
        settings->DockOrder = window->DockOrder;
13894
0
        settings->Collapsed = window->Collapsed;
13895
0
        settings->WantDelete = false;
13896
0
    }
13897
13898
    // Write to text buffer
13899
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
13900
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13901
0
    {
13902
0
        if (settings->WantDelete)
13903
0
            continue;
13904
0
        const char* settings_name = settings->GetName();
13905
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
13906
0
        if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13907
0
        {
13908
0
            buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
13909
0
            buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
13910
0
        }
13911
0
        if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13912
0
            buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
13913
0
        if (settings->Size.x != 0 || settings->Size.y != 0)
13914
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
13915
0
        buf->appendf("Collapsed=%d\n", settings->Collapsed);
13916
0
        if (settings->DockId != 0)
13917
0
        {
13918
            //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
13919
0
            if (settings->DockOrder == -1)
13920
0
                buf->appendf("DockId=0x%08X\n", settings->DockId);
13921
0
            else
13922
0
                buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
13923
0
            if (settings->ClassId != 0)
13924
0
                buf->appendf("ClassId=0x%08X\n", settings->ClassId);
13925
0
        }
13926
0
        buf->append("\n");
13927
0
    }
13928
0
}
13929
13930
13931
//-----------------------------------------------------------------------------
13932
// [SECTION] LOCALIZATION
13933
//-----------------------------------------------------------------------------
13934
13935
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
13936
1
{
13937
1
    ImGuiContext& g = *GImGui;
13938
10
    for (int n = 0; n < count; n++)
13939
9
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
13940
1
}
13941
13942
13943
//-----------------------------------------------------------------------------
13944
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
13945
//-----------------------------------------------------------------------------
13946
// - GetMainViewport()
13947
// - FindViewportByID()
13948
// - FindViewportByPlatformHandle()
13949
// - SetCurrentViewport() [Internal]
13950
// - SetWindowViewport() [Internal]
13951
// - GetWindowAlwaysWantOwnViewport() [Internal]
13952
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
13953
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
13954
// - TranslateWindowsInViewport() [Internal]
13955
// - ScaleWindowsInViewport() [Internal]
13956
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
13957
// - UpdateViewportsNewFrame() [Internal]
13958
// - UpdateViewportsEndFrame() [Internal]
13959
// - AddUpdateViewport() [Internal]
13960
// - WindowSelectViewport() [Internal]
13961
// - WindowSyncOwnedViewport() [Internal]
13962
// - UpdatePlatformWindows()
13963
// - RenderPlatformWindowsDefault()
13964
// - FindPlatformMonitorForPos() [Internal]
13965
// - FindPlatformMonitorForRect() [Internal]
13966
// - UpdateViewportPlatformMonitor() [Internal]
13967
// - DestroyPlatformWindow() [Internal]
13968
// - DestroyPlatformWindows()
13969
//-----------------------------------------------------------------------------
13970
13971
ImGuiViewport* ImGui::GetMainViewport()
13972
45.5k
{
13973
45.5k
    ImGuiContext& g = *GImGui;
13974
45.5k
    return g.Viewports[0];
13975
45.5k
}
13976
13977
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
13978
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
13979
18.0k
{
13980
18.0k
    ImGuiContext& g = *GImGui;
13981
18.0k
    for (int n = 0; n < g.Viewports.Size; n++)
13982
18.0k
        if (g.Viewports[n]->ID == id)
13983
18.0k
            return g.Viewports[n];
13984
0
    return NULL;
13985
18.0k
}
13986
13987
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
13988
0
{
13989
0
    ImGuiContext& g = *GImGui;
13990
0
    for (int i = 0; i != g.Viewports.Size; i++)
13991
0
        if (g.Viewports[i]->PlatformHandle == platform_handle)
13992
0
            return g.Viewports[i];
13993
0
    return NULL;
13994
0
}
13995
13996
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
13997
91.0k
{
13998
91.0k
    ImGuiContext& g = *GImGui;
13999
91.0k
    (void)current_window;
14000
14001
91.0k
    if (viewport)
14002
73.0k
        viewport->LastFrameActive = g.FrameCount;
14003
91.0k
    if (g.CurrentViewport == viewport)
14004
55.0k
        return;
14005
36.0k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
14006
36.0k
    g.CurrentViewport = viewport;
14007
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
14008
14009
    // Notify platform layer of viewport changes
14010
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
14011
36.0k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
14012
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
14013
36.0k
}
14014
14015
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14016
45.5k
{
14017
    // Abandon viewport
14018
45.5k
    if (window->ViewportOwned && window->Viewport->Window == window)
14019
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
14020
14021
45.5k
    window->Viewport = viewport;
14022
45.5k
    window->ViewportId = viewport->ID;
14023
45.5k
    window->ViewportOwned = (viewport->Window == window);
14024
45.5k
}
14025
14026
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
14027
0
{
14028
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
14029
0
    ImGuiContext& g = *GImGui;
14030
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
14031
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
14032
0
            if (!window->DockIsActive)
14033
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
14034
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
14035
0
                        return true;
14036
0
    return false;
14037
0
}
14038
14039
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
14040
0
{
14041
0
    ImGuiContext& g = *GImGui;
14042
0
    if (window->Viewport == viewport)
14043
0
        return false;
14044
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
14045
0
        return false;
14046
0
    if ((viewport->Flags & ImGuiViewportFlags_IsMinimized) != 0)
14047
0
        return false;
14048
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
14049
0
        return false;
14050
0
    if (GetWindowAlwaysWantOwnViewport(window))
14051
0
        return false;
14052
14053
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
14054
0
    for (int n = 0; n < g.Windows.Size; n++)
14055
0
    {
14056
0
        ImGuiWindow* window_behind = g.Windows[n];
14057
0
        if (window_behind == window)
14058
0
            break;
14059
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
14060
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
14061
0
                return false;
14062
0
    }
14063
14064
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
14065
0
    ImGuiViewportP* old_viewport = window->Viewport;
14066
0
    if (window->ViewportOwned)
14067
0
        for (int n = 0; n < g.Windows.Size; n++)
14068
0
            if (g.Windows[n]->Viewport == old_viewport)
14069
0
                SetWindowViewport(g.Windows[n], viewport);
14070
0
    SetWindowViewport(window, viewport);
14071
0
    BringWindowToDisplayFront(window);
14072
14073
0
    return true;
14074
0
}
14075
14076
// FIXME: handle 0 to N host viewports
14077
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
14078
0
{
14079
0
    ImGuiContext& g = *GImGui;
14080
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
14081
0
}
14082
14083
// Translate Dear ImGui windows when a Host Viewport has been moved
14084
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14085
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
14086
0
{
14087
0
    ImGuiContext& g = *GImGui;
14088
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
14089
14090
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
14091
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
14092
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
14093
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
14094
    // and so the window will appear to teleport when releasing the mouse.
14095
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
14096
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
14097
0
    ImVec2 delta_pos = new_pos - old_pos;
14098
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
14099
0
        if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
14100
0
            TranslateWindow(g.Windows[window_n], delta_pos);
14101
0
}
14102
14103
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
14104
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
14105
0
{
14106
0
    ImGuiContext& g = *GImGui;
14107
0
    if (viewport->Window)
14108
0
    {
14109
0
        ScaleWindow(viewport->Window, scale);
14110
0
    }
14111
0
    else
14112
0
    {
14113
0
        for (int i = 0; i != g.Windows.Size; i++)
14114
0
            if (g.Windows[i]->Viewport == viewport)
14115
0
                ScaleWindow(g.Windows[i], scale);
14116
0
    }
14117
0
}
14118
14119
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
14120
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14121
// B) It requires Platform_GetWindowFocus to be implemented by backend.
14122
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
14123
0
{
14124
0
    ImGuiContext& g = *GImGui;
14125
0
    ImGuiViewportP* best_candidate = NULL;
14126
0
    for (int n = 0; n < g.Viewports.Size; n++)
14127
0
    {
14128
0
        ImGuiViewportP* viewport = g.Viewports[n];
14129
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_IsMinimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
14130
0
            if (best_candidate == NULL || best_candidate->LastFocusedStampCount < viewport->LastFocusedStampCount)
14131
0
                best_candidate = viewport;
14132
0
    }
14133
0
    return best_candidate;
14134
0
}
14135
14136
// Update viewports and monitor infos
14137
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
14138
static void ImGui::UpdateViewportsNewFrame()
14139
18.0k
{
14140
18.0k
    ImGuiContext& g = *GImGui;
14141
18.0k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
14142
14143
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
14144
    // Update Focused status
14145
18.0k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
14146
18.0k
    if (viewports_enabled)
14147
0
    {
14148
0
        ImGuiViewportP* focused_viewport = NULL;
14149
0
        for (int n = 0; n < g.Viewports.Size; n++)
14150
0
        {
14151
0
            ImGuiViewportP* viewport = g.Viewports[n];
14152
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
14153
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
14154
0
            {
14155
0
                bool is_minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
14156
0
                if (is_minimized)
14157
0
                    viewport->Flags |= ImGuiViewportFlags_IsMinimized;
14158
0
                else
14159
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsMinimized;
14160
0
            }
14161
14162
            // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14163
            // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14164
0
            if (g.PlatformIO.Platform_GetWindowFocus && platform_funcs_available)
14165
0
            {
14166
0
                bool is_focused = g.PlatformIO.Platform_GetWindowFocus(viewport);
14167
0
                if (is_focused)
14168
0
                    viewport->Flags |= ImGuiViewportFlags_IsFocused;
14169
0
                else
14170
0
                    viewport->Flags &= ~ImGuiViewportFlags_IsFocused;
14171
0
                if (is_focused)
14172
0
                    focused_viewport = viewport;
14173
0
            }
14174
0
        }
14175
14176
        // Focused viewport has changed?
14177
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14178
0
        {
14179
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Focused viewport changed %08X -> %08X, attempting to apply our focus.\n", g.PlatformLastFocusedViewportId, focused_viewport->ID);
14180
0
            const ImGuiViewport* prev_focused_viewport = FindViewportByID(g.PlatformLastFocusedViewportId);
14181
0
            const bool prev_focused_has_been_destroyed = (prev_focused_viewport == NULL) || (prev_focused_viewport->PlatformWindowCreated == false);
14182
14183
            // Store a tag so we can infer z-order easily from all our windows
14184
            // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14185
            // will keep the front most stamp instead of losing it back to their parent viewport.
14186
0
            if (focused_viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14187
0
                focused_viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14188
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14189
14190
            // Focus associated dear imgui window
14191
            // - if focus didn't happen with a click within imgui boundaries, e.g. Clicking platform title bar. (#6299)
14192
            // - if focus didn't happen because we destroyed another window (#6462)
14193
            // FIXME: perhaps 'FocusTopMostWindowUnderOne()' can handle the 'focused_window->Window != NULL' case as well.
14194
0
            const bool apply_imgui_focus_on_focused_viewport = !IsAnyMouseDown() && !prev_focused_has_been_destroyed;
14195
0
            if (apply_imgui_focus_on_focused_viewport)
14196
0
            {
14197
0
                focused_viewport->LastFocusedHadNavWindow |= (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport); // Update so a window changing viewport won't lose focus.
14198
0
                ImGuiFocusRequestFlags focus_request_flags = ImGuiFocusRequestFlags_UnlessBelowModal | ImGuiFocusRequestFlags_RestoreFocusedChild;
14199
0
                if (focused_viewport->Window != NULL)
14200
0
                    FocusWindow(focused_viewport->Window, focus_request_flags);
14201
0
                else if (focused_viewport->LastFocusedHadNavWindow)
14202
0
                    FocusTopMostWindowUnderOne(NULL, NULL, focused_viewport, focus_request_flags); // Focus top most in viewport
14203
0
                else
14204
0
                    FocusWindow(NULL, focus_request_flags); // No window had focus last time viewport was focused
14205
0
            }
14206
0
        }
14207
0
        if (focused_viewport)
14208
0
            focused_viewport->LastFocusedHadNavWindow = (g.NavWindow != NULL) && (g.NavWindow->Viewport == focused_viewport);
14209
0
    }
14210
14211
    // Create/update main viewport with current platform position.
14212
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
14213
18.0k
    ImGuiViewportP* main_viewport = g.Viewports[0];
14214
18.0k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
14215
18.0k
    IM_ASSERT(main_viewport->Window == NULL);
14216
18.0k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
14217
18.0k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
14218
18.0k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_IsMinimized))
14219
0
    {
14220
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
14221
0
        main_viewport_size = main_viewport->Size;
14222
0
    }
14223
18.0k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
14224
14225
18.0k
    g.CurrentDpiScale = 0.0f;
14226
18.0k
    g.CurrentViewport = NULL;
14227
18.0k
    g.MouseViewport = NULL;
14228
36.0k
    for (int n = 0; n < g.Viewports.Size; n++)
14229
18.0k
    {
14230
18.0k
        ImGuiViewportP* viewport = g.Viewports[n];
14231
18.0k
        viewport->Idx = n;
14232
14233
        // Erase unused viewports
14234
18.0k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
14235
0
        {
14236
0
            DestroyViewport(viewport);
14237
0
            n--;
14238
0
            continue;
14239
0
        }
14240
14241
18.0k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
14242
18.0k
        if (viewports_enabled)
14243
0
        {
14244
            // Update Position and Size (from Platform Window to ImGui) if requested.
14245
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
14246
0
            if (!(viewport->Flags & ImGuiViewportFlags_IsMinimized) && platform_funcs_available)
14247
0
            {
14248
                // Viewport->WorkPos and WorkSize will be updated below
14249
0
                if (viewport->PlatformRequestMove)
14250
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
14251
0
                if (viewport->PlatformRequestResize)
14252
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
14253
0
            }
14254
0
        }
14255
14256
        // Update/copy monitor info
14257
18.0k
        UpdateViewportPlatformMonitor(viewport);
14258
14259
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
14260
18.0k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
14261
18.0k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
14262
18.0k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
14263
18.0k
        viewport->UpdateWorkRect();
14264
14265
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
14266
18.0k
        viewport->Alpha = 1.0f;
14267
14268
        // Translate Dear ImGui windows when a Host Viewport has been moved
14269
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
14270
18.0k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
14271
18.0k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
14272
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
14273
14274
        // Update DPI scale
14275
18.0k
        float new_dpi_scale;
14276
18.0k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
14277
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
14278
18.0k
        else if (viewport->PlatformMonitor != -1)
14279
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14280
18.0k
        else
14281
18.0k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
14282
18.0k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
14283
0
        {
14284
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
14285
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
14286
0
                ScaleWindowsInViewport(viewport, scale_factor);
14287
            //if (viewport == GetMainViewport())
14288
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
14289
14290
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
14291
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
14292
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
14293
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
14294
            //    g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
14295
0
        }
14296
18.0k
        viewport->DpiScale = new_dpi_scale;
14297
18.0k
    }
14298
14299
    // Update fallback monitor
14300
18.0k
    if (g.PlatformIO.Monitors.Size == 0)
14301
18.0k
    {
14302
18.0k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
14303
18.0k
        monitor->MainPos = main_viewport->Pos;
14304
18.0k
        monitor->MainSize = main_viewport->Size;
14305
18.0k
        monitor->WorkPos = main_viewport->WorkPos;
14306
18.0k
        monitor->WorkSize = main_viewport->WorkSize;
14307
18.0k
        monitor->DpiScale = main_viewport->DpiScale;
14308
18.0k
    }
14309
14310
18.0k
    if (!viewports_enabled)
14311
18.0k
    {
14312
18.0k
        g.MouseViewport = main_viewport;
14313
18.0k
        return;
14314
18.0k
    }
14315
14316
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
14317
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
14318
0
    ImGuiViewportP* viewport_hovered = NULL;
14319
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
14320
0
    {
14321
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
14322
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14323
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
14324
0
    }
14325
0
    else
14326
0
    {
14327
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
14328
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
14329
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
14330
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
14331
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
14332
0
    }
14333
0
    if (viewport_hovered != NULL)
14334
0
        g.MouseLastHoveredViewport = viewport_hovered;
14335
0
    else if (g.MouseLastHoveredViewport == NULL)
14336
0
        g.MouseLastHoveredViewport = g.Viewports[0];
14337
14338
    // Update mouse reference viewport
14339
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
14340
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
14341
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
14342
0
        g.MouseViewport = g.MovingWindow->Viewport;
14343
0
    else
14344
0
        g.MouseViewport = g.MouseLastHoveredViewport;
14345
14346
    // When dragging something, always refer to the last hovered viewport.
14347
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
14348
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
14349
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
14350
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
14351
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
14352
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
14353
0
        viewport_hovered = g.MouseLastHoveredViewport;
14354
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
14355
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
14356
0
            g.MouseViewport = viewport_hovered;
14357
14358
0
    IM_ASSERT(g.MouseViewport != NULL);
14359
0
}
14360
14361
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
14362
static void ImGui::UpdateViewportsEndFrame()
14363
18.0k
{
14364
18.0k
    ImGuiContext& g = *GImGui;
14365
18.0k
    g.PlatformIO.Viewports.resize(0);
14366
36.0k
    for (int i = 0; i < g.Viewports.Size; i++)
14367
18.0k
    {
14368
18.0k
        ImGuiViewportP* viewport = g.Viewports[i];
14369
18.0k
        viewport->LastPos = viewport->Pos;
14370
18.0k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
14371
0
            if (i > 0) // Always include main viewport in the list
14372
0
                continue;
14373
18.0k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
14374
0
            continue;
14375
18.0k
        if (i > 0)
14376
18.0k
            IM_ASSERT(viewport->Window != NULL);
14377
18.0k
        g.PlatformIO.Viewports.push_back(viewport);
14378
18.0k
    }
14379
18.0k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
14380
18.0k
}
14381
14382
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
14383
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
14384
18.0k
{
14385
18.0k
    ImGuiContext& g = *GImGui;
14386
18.0k
    IM_ASSERT(id != 0);
14387
14388
18.0k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
14389
18.0k
    if (window != NULL)
14390
0
    {
14391
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
14392
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
14393
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
14394
0
            flags |= ImGuiViewportFlags_NoInputs;
14395
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
14396
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14397
0
    }
14398
14399
18.0k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
14400
18.0k
    if (viewport)
14401
18.0k
    {
14402
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
14403
18.0k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14404
18.0k
            viewport->Pos = pos;
14405
18.0k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
14406
18.0k
            viewport->Size = size;
14407
18.0k
        viewport->Flags = flags | (viewport->Flags & (ImGuiViewportFlags_IsMinimized | ImGuiViewportFlags_IsFocused)); // Preserve existing flags
14408
18.0k
    }
14409
0
    else
14410
0
    {
14411
        // New viewport
14412
0
        viewport = IM_NEW(ImGuiViewportP)();
14413
0
        viewport->ID = id;
14414
0
        viewport->Idx = g.Viewports.Size;
14415
0
        viewport->Pos = viewport->LastPos = pos;
14416
0
        viewport->Size = size;
14417
0
        viewport->Flags = flags;
14418
0
        UpdateViewportPlatformMonitor(viewport);
14419
0
        g.Viewports.push_back(viewport);
14420
0
        g.ViewportCreatedCount++;
14421
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
14422
14423
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
14424
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
14425
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
14426
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
14427
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
14428
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
14429
14430
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
14431
        // This is so we can select an appropriate font size on the first frame of our window lifetime
14432
0
        if (viewport->PlatformMonitor != -1)
14433
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
14434
0
    }
14435
14436
18.0k
    viewport->Window = window;
14437
18.0k
    viewport->LastFrameActive = g.FrameCount;
14438
18.0k
    viewport->UpdateWorkRect();
14439
18.0k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
14440
14441
18.0k
    if (window != NULL)
14442
0
        window->ViewportOwned = true;
14443
14444
18.0k
    return viewport;
14445
18.0k
}
14446
14447
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
14448
0
{
14449
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
14450
0
    ImGuiContext& g = *GImGui;
14451
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
14452
0
    {
14453
0
        ImGuiWindow* window = g.Windows[window_n];
14454
0
        if (window->Viewport != viewport)
14455
0
            continue;
14456
0
        window->Viewport = NULL;
14457
0
        window->ViewportOwned = false;
14458
0
    }
14459
0
    if (viewport == g.MouseLastHoveredViewport)
14460
0
        g.MouseLastHoveredViewport = NULL;
14461
14462
    // Destroy
14463
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14464
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
14465
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
14466
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
14467
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
14468
0
    IM_DELETE(viewport);
14469
0
}
14470
14471
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
14472
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
14473
45.5k
{
14474
45.5k
    ImGuiContext& g = *GImGui;
14475
45.5k
    ImGuiWindowFlags flags = window->Flags;
14476
45.5k
    window->ViewportAllowPlatformMonitorExtend = -1;
14477
14478
    // Restore main viewport if multi-viewport is not supported by the backend
14479
45.5k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
14480
45.5k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14481
45.5k
    {
14482
45.5k
        SetWindowViewport(window, main_viewport);
14483
45.5k
        return;
14484
45.5k
    }
14485
0
    window->ViewportOwned = false;
14486
14487
    // Appearing popups reset their viewport so they can inherit again
14488
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
14489
0
    {
14490
0
        window->Viewport = NULL;
14491
0
        window->ViewportId = 0;
14492
0
    }
14493
14494
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
14495
0
    {
14496
        // By default inherit from parent window
14497
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
14498
0
            window->Viewport = window->ParentWindow->Viewport;
14499
14500
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
14501
0
        if (window->Viewport == NULL && window->ViewportId != 0)
14502
0
        {
14503
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
14504
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
14505
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
14506
0
        }
14507
0
    }
14508
14509
0
    bool lock_viewport = false;
14510
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
14511
0
    {
14512
        // Code explicitly request a viewport
14513
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
14514
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
14515
0
        if (window->Viewport && (window->Flags & ImGuiWindowFlags_DockNodeHost) != 0 && window->Viewport->Window != NULL)
14516
0
        {
14517
0
            window->Viewport->Window = window;
14518
0
            window->Viewport->ID = window->ViewportId = window->ID; // Overwrite ID (always owned by node)
14519
0
        }
14520
0
        lock_viewport = true;
14521
0
    }
14522
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14523
0
    {
14524
        // Always inherit viewport from parent window
14525
0
        if (window->DockNode && window->DockNode->HostWindow)
14526
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14527
0
        window->Viewport = window->ParentWindow->Viewport;
14528
0
    }
14529
0
    else if (window->DockNode && window->DockNode->HostWindow)
14530
0
    {
14531
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14532
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14533
0
    }
14534
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14535
0
    {
14536
0
        window->Viewport = g.MouseViewport;
14537
0
    }
14538
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14539
0
    {
14540
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14541
0
    }
14542
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14543
0
    {
14544
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14545
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14546
0
    }
14547
0
    else
14548
0
    {
14549
        // Merge into host viewport?
14550
        // We cannot test window->ViewportOwned as it set lower in the function.
14551
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14552
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14553
0
        if (try_to_merge_into_host_viewport)
14554
0
            UpdateTryMergeWindowIntoHostViewports(window);
14555
0
    }
14556
14557
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14558
0
    if (window->Viewport == NULL)
14559
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14560
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14561
14562
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14563
0
    if (!lock_viewport)
14564
0
    {
14565
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14566
0
        {
14567
            // We need to take account of the possibility that mouse may become invalid.
14568
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14569
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14570
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14571
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14572
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14573
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14574
0
            else
14575
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14576
0
        }
14577
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14578
0
        {
14579
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14580
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14581
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14582
0
            {
14583
                // Steal/transfer ownership
14584
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14585
0
                window->Viewport->Window = window;
14586
0
                window->Viewport->ID = window->ID;
14587
0
                window->Viewport->LastNameHash = 0;
14588
0
            }
14589
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14590
0
            {
14591
                // New viewport
14592
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14593
0
            }
14594
0
        }
14595
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14596
0
        {
14597
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14598
            // Child windows are kept contained within their parent.
14599
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14600
0
        }
14601
0
    }
14602
14603
    // Update flags
14604
0
    window->ViewportOwned = (window == window->Viewport->Window);
14605
0
    window->ViewportId = window->Viewport->ID;
14606
14607
    // If the OS window has a title bar, hide our imgui title bar
14608
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14609
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14610
0
}
14611
14612
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14613
0
{
14614
0
    ImGuiContext& g = *GImGui;
14615
14616
0
    bool viewport_rect_changed = false;
14617
14618
    // Synchronize window --> viewport in most situations
14619
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14620
0
    if (window->Viewport->PlatformRequestMove)
14621
0
    {
14622
0
        window->Pos = window->Viewport->Pos;
14623
0
        MarkIniSettingsDirty(window);
14624
0
    }
14625
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14626
0
    {
14627
0
        viewport_rect_changed = true;
14628
0
        window->Viewport->Pos = window->Pos;
14629
0
    }
14630
14631
0
    if (window->Viewport->PlatformRequestResize)
14632
0
    {
14633
0
        window->Size = window->SizeFull = window->Viewport->Size;
14634
0
        MarkIniSettingsDirty(window);
14635
0
    }
14636
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14637
0
    {
14638
0
        viewport_rect_changed = true;
14639
0
        window->Viewport->Size = window->Size;
14640
0
    }
14641
0
    window->Viewport->UpdateWorkRect();
14642
14643
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14644
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14645
0
    if (viewport_rect_changed)
14646
0
        UpdateViewportPlatformMonitor(window->Viewport);
14647
14648
    // Update common viewport flags
14649
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14650
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14651
0
    ImGuiWindowFlags window_flags = window->Flags;
14652
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14653
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14654
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14655
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14656
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14657
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14658
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14659
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14660
14661
    // Not correct to set modal as topmost because:
14662
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14663
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14664
    //if (flags & ImGuiWindowFlags_Modal)
14665
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14666
14667
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14668
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14669
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14670
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14671
0
    if (is_short_lived_floating_window && !is_modal)
14672
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14673
14674
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14675
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14676
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14677
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14678
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14679
14680
    // We can also tell the backend that clearing the platform window won't be necessary,
14681
    // as our window background is filling the viewport and we have disabled BgAlpha.
14682
    // FIXME: Work on support for per-viewport transparency (#2766)
14683
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14684
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14685
14686
0
    window->Viewport->Flags = viewport_flags;
14687
14688
    // Update parent viewport ID
14689
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14690
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14691
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14692
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14693
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14694
0
    else
14695
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14696
0
}
14697
14698
// Called by user at the end of the main loop, after EndFrame()
14699
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14700
void ImGui::UpdatePlatformWindows()
14701
0
{
14702
0
    ImGuiContext& g = *GImGui;
14703
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14704
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14705
0
    g.FrameCountPlatformEnded = g.FrameCount;
14706
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14707
0
        return;
14708
14709
    // Create/resize/destroy platform windows to match each active viewport.
14710
    // Skip the main viewport (index 0), which is always fully handled by the application!
14711
0
    for (int i = 1; i < g.Viewports.Size; i++)
14712
0
    {
14713
0
        ImGuiViewportP* viewport = g.Viewports[i];
14714
14715
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14716
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14717
0
        bool destroy_platform_window = false;
14718
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14719
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14720
0
        if (destroy_platform_window)
14721
0
        {
14722
0
            DestroyPlatformWindow(viewport);
14723
0
            continue;
14724
0
        }
14725
14726
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14727
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14728
0
            continue;
14729
14730
        // Create window
14731
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14732
0
        if (is_new_platform_window)
14733
0
        {
14734
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14735
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14736
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14737
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14738
0
            g.PlatformWindowsCreatedCount++;
14739
0
            viewport->LastNameHash = 0;
14740
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14741
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14742
0
            viewport->PlatformWindowCreated = true;
14743
0
        }
14744
14745
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14746
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14747
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14748
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14749
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14750
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14751
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14752
0
        viewport->LastPlatformPos = viewport->Pos;
14753
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14754
14755
        // Update title bar (if it changed)
14756
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14757
0
        {
14758
0
            const char* title_begin = window_for_title->Name;
14759
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14760
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14761
0
            if (viewport->LastNameHash != title_hash)
14762
0
            {
14763
0
                char title_end_backup_c = *title_end;
14764
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14765
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14766
0
                *title_end = title_end_backup_c;
14767
0
                viewport->LastNameHash = title_hash;
14768
0
            }
14769
0
        }
14770
14771
        // Update alpha (if it changed)
14772
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14773
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14774
0
        viewport->LastAlpha = viewport->Alpha;
14775
14776
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14777
0
        if (g.PlatformIO.Platform_UpdateWindow)
14778
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
14779
14780
0
        if (is_new_platform_window)
14781
0
        {
14782
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
14783
0
            if (g.FrameCount < 3)
14784
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14785
14786
            // Show window
14787
0
            g.PlatformIO.Platform_ShowWindow(viewport);
14788
14789
            // Even without focus, we assume the window becomes front-most.
14790
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
14791
0
            if (viewport->LastFocusedStampCount != g.ViewportFocusedStampCount)
14792
0
                viewport->LastFocusedStampCount = ++g.ViewportFocusedStampCount;
14793
0
        }
14794
14795
        // Clear request flags
14796
0
        viewport->ClearRequestFlags();
14797
0
    }
14798
0
}
14799
14800
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
14801
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
14802
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
14803
//
14804
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14805
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14806
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14807
//            MyRenderFunction(platform_io.Viewports[i], my_args);
14808
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14809
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14810
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
14811
//
14812
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
14813
0
{
14814
    // Skip the main viewport (index 0), which is always fully handled by the application!
14815
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14816
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14817
0
    {
14818
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14819
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
14820
0
            continue;
14821
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
14822
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
14823
0
    }
14824
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14825
0
    {
14826
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14827
0
        if (viewport->Flags & ImGuiViewportFlags_IsMinimized)
14828
0
            continue;
14829
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
14830
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
14831
0
    }
14832
0
}
14833
14834
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
14835
0
{
14836
0
    ImGuiContext& g = *GImGui;
14837
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
14838
0
    {
14839
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14840
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
14841
0
            return monitor_n;
14842
0
    }
14843
0
    return -1;
14844
0
}
14845
14846
// Search for the monitor with the largest intersection area with the given rectangle
14847
// We generally try to avoid searching loops but the monitor count should be very small here
14848
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
14849
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
14850
18.0k
{
14851
18.0k
    ImGuiContext& g = *GImGui;
14852
14853
18.0k
    const int monitor_count = g.PlatformIO.Monitors.Size;
14854
18.0k
    if (monitor_count <= 1)
14855
18.0k
        return monitor_count - 1;
14856
14857
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
14858
    // This is necessary for tooltips which always resize down to zero at first.
14859
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
14860
0
    int best_monitor_n = -1;
14861
0
    float best_monitor_surface = 0.001f;
14862
14863
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
14864
0
    {
14865
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14866
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
14867
0
        if (monitor_rect.Contains(rect))
14868
0
            return monitor_n;
14869
0
        ImRect overlapping_rect = rect;
14870
0
        overlapping_rect.ClipWithFull(monitor_rect);
14871
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
14872
0
        if (overlapping_surface < best_monitor_surface)
14873
0
            continue;
14874
0
        best_monitor_surface = overlapping_surface;
14875
0
        best_monitor_n = monitor_n;
14876
0
    }
14877
0
    return best_monitor_n;
14878
0
}
14879
14880
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
14881
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
14882
18.0k
{
14883
18.0k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
14884
18.0k
}
14885
14886
// Return value is always != NULL, but don't hold on it across frames.
14887
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
14888
0
{
14889
0
    ImGuiContext& g = *GImGui;
14890
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
14891
0
    int monitor_idx = viewport->PlatformMonitor;
14892
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
14893
0
        return &g.PlatformIO.Monitors[monitor_idx];
14894
0
    return &g.FallbackMonitor;
14895
0
}
14896
14897
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
14898
0
{
14899
0
    ImGuiContext& g = *GImGui;
14900
0
    if (viewport->PlatformWindowCreated)
14901
0
    {
14902
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Destroy Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14903
0
        if (g.PlatformIO.Renderer_DestroyWindow)
14904
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
14905
0
        if (g.PlatformIO.Platform_DestroyWindow)
14906
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
14907
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
14908
14909
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
14910
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
14911
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
14912
0
            viewport->PlatformWindowCreated = false;
14913
0
    }
14914
0
    else
14915
0
    {
14916
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
14917
0
    }
14918
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
14919
0
    viewport->ClearRequestFlags();
14920
0
}
14921
14922
void ImGui::DestroyPlatformWindows()
14923
0
{
14924
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
14925
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
14926
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
14927
    // code to operator a consistent manner.
14928
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
14929
    // crashing if it doesn't have data stored.
14930
0
    ImGuiContext& g = *GImGui;
14931
0
    for (int i = 0; i < g.Viewports.Size; i++)
14932
0
        DestroyPlatformWindow(g.Viewports[i]);
14933
0
}
14934
14935
14936
//-----------------------------------------------------------------------------
14937
// [SECTION] DOCKING
14938
//-----------------------------------------------------------------------------
14939
// Docking: Internal Types
14940
// Docking: Forward Declarations
14941
// Docking: ImGuiDockContext
14942
// Docking: ImGuiDockContext Docking/Undocking functions
14943
// Docking: ImGuiDockNode
14944
// Docking: ImGuiDockNode Tree manipulation functions
14945
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
14946
// Docking: Builder Functions
14947
// Docking: Begin/End Support Functions (called from Begin/End)
14948
// Docking: Settings
14949
//-----------------------------------------------------------------------------
14950
14951
//-----------------------------------------------------------------------------
14952
// Typical Docking call flow: (root level is generally public API):
14953
//-----------------------------------------------------------------------------
14954
// - NewFrame()                               new dear imgui frame
14955
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
14956
//    | - DockContextProcessUndockWindow()    - process one window undocking request
14957
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
14958
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
14959
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
14960
//    | - DockContextProcessDock()            - process one docking request
14961
//    | - DockNodeUpdate()
14962
//    |   - DockNodeUpdateForRootNode()
14963
//    |     - DockNodeUpdateFlagsAndCollapse()
14964
//    |     - DockNodeFindInfo()
14965
//    |   - destroy unused node or tab bar
14966
//    |   - create dock node host window
14967
//    |      - Begin() etc.
14968
//    |   - DockNodeStartMouseMovingWindow()
14969
//    |   - DockNodeTreeUpdatePosSize()
14970
//    |   - DockNodeTreeUpdateSplitter()
14971
//    |   - draw node background
14972
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
14973
//    |     - DockNodeAddTabBar()
14974
//    |     - DockNodeUpdateWindowMenu()
14975
//    |     - DockNodeCalcTabBarLayout()
14976
//    |     - BeginTabBarEx()
14977
//    |     - TabItemEx() calls
14978
//    |     - EndTabBar()
14979
//    |   - BeginDockableDragDropTarget()
14980
//    |      - DockNodeUpdate()               - recurse into child nodes...
14981
//-----------------------------------------------------------------------------
14982
// - DockSpace()                              user submit a dockspace into a window
14983
//    | Begin(Child)                          - create a child window
14984
//    | DockNodeUpdate()                      - call main dock node update function
14985
//    | End(Child)
14986
//    | ItemSize()
14987
//-----------------------------------------------------------------------------
14988
// - Begin()
14989
//    | BeginDocked()
14990
//    | BeginDockableDragDropSource()
14991
//    | BeginDockableDragDropTarget()
14992
//    | - DockNodePreviewDockRender()
14993
//-----------------------------------------------------------------------------
14994
// - EndFrame()
14995
//    | DockContextEndFrame()
14996
//-----------------------------------------------------------------------------
14997
14998
//-----------------------------------------------------------------------------
14999
// Docking: Internal Types
15000
//-----------------------------------------------------------------------------
15001
// - ImGuiDockRequestType
15002
// - ImGuiDockRequest
15003
// - ImGuiDockPreviewData
15004
// - ImGuiDockNodeSettings
15005
// - ImGuiDockContext
15006
//-----------------------------------------------------------------------------
15007
15008
enum ImGuiDockRequestType
15009
{
15010
    ImGuiDockRequestType_None = 0,
15011
    ImGuiDockRequestType_Dock,
15012
    ImGuiDockRequestType_Undock,
15013
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
15014
};
15015
15016
struct ImGuiDockRequest
15017
{
15018
    ImGuiDockRequestType    Type;
15019
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
15020
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
15021
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
15022
    ImGuiDir                DockSplitDir;
15023
    float                   DockSplitRatio;
15024
    bool                    DockSplitOuter;
15025
    ImGuiWindow*            UndockTargetWindow;
15026
    ImGuiDockNode*          UndockTargetNode;
15027
15028
    ImGuiDockRequest()
15029
0
    {
15030
0
        Type = ImGuiDockRequestType_None;
15031
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
15032
0
        DockTargetNode = UndockTargetNode = NULL;
15033
0
        DockSplitDir = ImGuiDir_None;
15034
0
        DockSplitRatio = 0.5f;
15035
0
        DockSplitOuter = false;
15036
0
    }
15037
};
15038
15039
struct ImGuiDockPreviewData
15040
{
15041
    ImGuiDockNode   FutureNode;
15042
    bool            IsDropAllowed;
15043
    bool            IsCenterAvailable;
15044
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
15045
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
15046
    ImGuiDockNode*  SplitNode;
15047
    ImGuiDir        SplitDir;
15048
    float           SplitRatio;
15049
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
15050
15051
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
15052
};
15053
15054
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
15055
struct ImGuiDockNodeSettings
15056
{
15057
    ImGuiID             ID;
15058
    ImGuiID             ParentNodeId;
15059
    ImGuiID             ParentWindowId;
15060
    ImGuiID             SelectedTabId;
15061
    signed char         SplitAxis;
15062
    char                Depth;
15063
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
15064
    ImVec2ih            Pos;
15065
    ImVec2ih            Size;
15066
    ImVec2ih            SizeRef;
15067
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
15068
};
15069
15070
//-----------------------------------------------------------------------------
15071
// Docking: Forward Declarations
15072
//-----------------------------------------------------------------------------
15073
15074
namespace ImGui
15075
{
15076
    // ImGuiDockContext
15077
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
15078
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
15079
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
15080
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
15081
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
15082
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
15083
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
15084
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
15085
15086
    // ImGuiDockNode
15087
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
15088
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15089
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
15090
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
15091
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
15092
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
15093
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
15094
    static void             DockNodeUpdate(ImGuiDockNode* node);
15095
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
15096
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
15097
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
15098
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
15099
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
15100
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
15101
    static void             DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
15102
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
15103
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
15104
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
15105
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
15106
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
15107
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
15108
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
15109
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
15110
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
15111
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
15112
15113
    // ImGuiDockNode tree manipulations
15114
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
15115
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
15116
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
15117
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
15118
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
15119
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
15120
15121
    // Settings
15122
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
15123
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
15124
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
15125
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
15126
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
15127
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
15128
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
15129
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
15130
}
15131
15132
//-----------------------------------------------------------------------------
15133
// Docking: ImGuiDockContext
15134
//-----------------------------------------------------------------------------
15135
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
15136
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
15137
// At boot time only, we run a simple GC to remove nodes that have no references.
15138
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
15139
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
15140
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
15141
//-----------------------------------------------------------------------------
15142
// - DockContextInitialize()
15143
// - DockContextShutdown()
15144
// - DockContextClearNodes()
15145
// - DockContextRebuildNodes()
15146
// - DockContextNewFrameUpdateUndocking()
15147
// - DockContextNewFrameUpdateDocking()
15148
// - DockContextEndFrame()
15149
// - DockContextFindNodeByID()
15150
// - DockContextBindNodeToWindow()
15151
// - DockContextGenNodeID()
15152
// - DockContextAddNode()
15153
// - DockContextRemoveNode()
15154
// - ImGuiDockContextPruneNodeData
15155
// - DockContextPruneUnusedSettingsNodes()
15156
// - DockContextBuildNodesFromSettings()
15157
// - DockContextBuildAddWindowsToNodes()
15158
//-----------------------------------------------------------------------------
15159
15160
void ImGui::DockContextInitialize(ImGuiContext* ctx)
15161
1
{
15162
1
    ImGuiContext& g = *ctx;
15163
15164
    // Add .ini handle for persistent docking data
15165
1
    ImGuiSettingsHandler ini_handler;
15166
1
    ini_handler.TypeName = "Docking";
15167
1
    ini_handler.TypeHash = ImHashStr("Docking");
15168
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
15169
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
15170
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
15171
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
15172
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
15173
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
15174
1
    g.SettingsHandlers.push_back(ini_handler);
15175
15176
1
    g.DockNodeWindowMenuHandler = &DockNodeWindowMenuHandler_Default;
15177
1
}
15178
15179
void ImGui::DockContextShutdown(ImGuiContext* ctx)
15180
0
{
15181
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15182
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15183
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15184
0
            IM_DELETE(node);
15185
0
}
15186
15187
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
15188
0
{
15189
0
    IM_UNUSED(ctx);
15190
0
    IM_ASSERT(ctx == GImGui);
15191
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
15192
0
    DockBuilderRemoveNodeChildNodes(root_id);
15193
0
}
15194
15195
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
15196
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
15197
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
15198
0
{
15199
0
    ImGuiContext& g = *ctx;
15200
0
    ImGuiDockContext* dc = &ctx->DockContext;
15201
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
15202
0
    SaveIniSettingsToMemory();
15203
0
    ImGuiID root_id = 0; // Rebuild all
15204
0
    DockContextClearNodes(ctx, root_id, false);
15205
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
15206
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
15207
0
}
15208
15209
// Docking context update function, called by NewFrame()
15210
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
15211
18.0k
{
15212
18.0k
    ImGuiContext& g = *ctx;
15213
18.0k
    ImGuiDockContext* dc = &ctx->DockContext;
15214
18.0k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15215
0
    {
15216
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
15217
0
            DockContextClearNodes(ctx, 0, true);
15218
0
        return;
15219
0
    }
15220
15221
    // Setting NoSplit at runtime merges all nodes
15222
18.0k
    if (g.IO.ConfigDockingNoSplit)
15223
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
15224
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15225
0
                if (node->IsRootNode() && node->IsSplitNode())
15226
0
                {
15227
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
15228
                    //dc->WantFullRebuild = true;
15229
0
                }
15230
15231
    // Process full rebuild
15232
#if 0
15233
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
15234
        dc->WantFullRebuild = true;
15235
#endif
15236
18.0k
    if (dc->WantFullRebuild)
15237
0
    {
15238
0
        DockContextRebuildNodes(ctx);
15239
0
        dc->WantFullRebuild = false;
15240
0
    }
15241
15242
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
15243
18.0k
    for (int n = 0; n < dc->Requests.Size; n++)
15244
0
    {
15245
0
        ImGuiDockRequest* req = &dc->Requests[n];
15246
0
        if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
15247
0
            DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
15248
0
        else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
15249
0
            DockContextProcessUndockNode(ctx, req->UndockTargetNode);
15250
0
    }
15251
18.0k
}
15252
15253
// Docking context update function, called by NewFrame()
15254
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
15255
18.0k
{
15256
18.0k
    ImGuiContext& g = *ctx;
15257
18.0k
    ImGuiDockContext* dc  = &ctx->DockContext;
15258
18.0k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
15259
0
        return;
15260
15261
    // [DEBUG] Store hovered dock node.
15262
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
15263
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
15264
18.0k
    g.DebugHoveredDockNode = NULL;
15265
18.0k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
15266
352
    {
15267
352
        if (hovered_window->DockNodeAsHost)
15268
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
15269
352
        else if (hovered_window->RootWindow->DockNode)
15270
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
15271
352
    }
15272
15273
    // Process Docking requests
15274
18.0k
    for (int n = 0; n < dc->Requests.Size; n++)
15275
0
        if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
15276
0
            DockContextProcessDock(ctx, &dc->Requests[n]);
15277
18.0k
    dc->Requests.resize(0);
15278
15279
    // Create windows for each automatic docking nodes
15280
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
15281
18.0k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15282
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15283
0
            if (node->IsFloatingNode())
15284
0
                DockNodeUpdate(node);
15285
18.0k
}
15286
15287
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
15288
18.0k
{
15289
    // Draw backgrounds of node missing their window
15290
18.0k
    ImGuiContext& g = *ctx;
15291
18.0k
    ImGuiDockContext* dc = &g.DockContext;
15292
18.0k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
15293
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
15294
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
15295
0
            {
15296
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
15297
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), DOCKING_SPLITTER_SIZE);
15298
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
15299
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
15300
0
            }
15301
18.0k
}
15302
15303
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
15304
0
{
15305
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
15306
0
}
15307
15308
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
15309
0
{
15310
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
15311
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
15312
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
15313
0
    ImGuiID id = 0x0001;
15314
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
15315
0
        id++;
15316
0
    return id;
15317
0
}
15318
15319
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
15320
0
{
15321
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
15322
0
    ImGuiContext& g = *ctx;
15323
0
    if (id == 0)
15324
0
        id = DockContextGenNodeID(ctx);
15325
0
    else
15326
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
15327
15328
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
15329
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
15330
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
15331
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
15332
0
    return node;
15333
0
}
15334
15335
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
15336
0
{
15337
0
    ImGuiContext& g = *ctx;
15338
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15339
15340
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
15341
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
15342
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
15343
0
    IM_ASSERT(node->Windows.Size == 0);
15344
15345
0
    if (node->HostWindow)
15346
0
        node->HostWindow->DockNodeAsHost = NULL;
15347
15348
0
    ImGuiDockNode* parent_node = node->ParentNode;
15349
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
15350
0
    if (merge)
15351
0
    {
15352
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
15353
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
15354
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
15355
0
    }
15356
0
    else
15357
0
    {
15358
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
15359
0
            if (parent_node->ChildNodes[n] == node)
15360
0
                node->ParentNode->ChildNodes[n] = NULL;
15361
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
15362
0
        IM_DELETE(node);
15363
0
    }
15364
0
}
15365
15366
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
15367
0
{
15368
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
15369
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
15370
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
15371
0
}
15372
15373
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
15374
struct ImGuiDockContextPruneNodeData
15375
{
15376
    int         CountWindows, CountChildWindows, CountChildNodes;
15377
    ImGuiID     RootId;
15378
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
15379
};
15380
15381
// Garbage collect unused nodes (run once at init time)
15382
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
15383
0
{
15384
0
    ImGuiContext& g = *ctx;
15385
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15386
0
    IM_ASSERT(g.Windows.Size == 0);
15387
15388
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
15389
0
    pool.Reserve(dc->NodesSettings.Size);
15390
15391
    // Count child nodes and compute RootID
15392
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15393
0
    {
15394
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15395
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
15396
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
15397
0
        if (settings->ParentNodeId)
15398
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
15399
0
    }
15400
15401
    // Count reference to dock ids from dockspaces
15402
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
15403
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15404
0
    {
15405
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15406
0
        if (settings->ParentWindowId != 0)
15407
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
15408
0
                if (window_settings->DockId)
15409
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
15410
0
                        data->CountChildNodes++;
15411
0
    }
15412
15413
    // Count reference to dock ids from window settings
15414
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
15415
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
15416
0
        if (ImGuiID dock_id = settings->DockId)
15417
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
15418
0
            {
15419
0
                data->CountWindows++;
15420
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
15421
0
                    data_root->CountChildWindows++;
15422
0
            }
15423
15424
    // Prune
15425
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
15426
0
    {
15427
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
15428
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
15429
0
        if (data->CountWindows > 1)
15430
0
            continue;
15431
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
15432
15433
0
        bool remove = false;
15434
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
15435
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
15436
0
        remove |= (data_root->CountChildWindows == 0);
15437
0
        if (remove)
15438
0
        {
15439
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
15440
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
15441
0
            settings->ID = 0;
15442
0
        }
15443
0
    }
15444
0
}
15445
15446
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
15447
0
{
15448
    // Build nodes
15449
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
15450
0
    {
15451
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
15452
0
        if (settings->ID == 0)
15453
0
            continue;
15454
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
15455
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
15456
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
15457
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
15458
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
15459
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
15460
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
15461
0
            node->ParentNode->ChildNodes[0] = node;
15462
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
15463
0
            node->ParentNode->ChildNodes[1] = node;
15464
0
        node->SelectedTabId = settings->SelectedTabId;
15465
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
15466
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
15467
15468
        // Bind host window immediately if it already exist (in case of a rebuild)
15469
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
15470
0
        char host_window_title[20];
15471
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15472
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
15473
0
    }
15474
0
}
15475
15476
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
15477
0
{
15478
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
15479
0
    ImGuiContext& g = *ctx;
15480
0
    for (int n = 0; n < g.Windows.Size; n++)
15481
0
    {
15482
0
        ImGuiWindow* window = g.Windows[n];
15483
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
15484
0
            continue;
15485
0
        if (window->DockNode != NULL)
15486
0
            continue;
15487
15488
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
15489
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
15490
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
15491
0
            DockNodeAddWindow(node, window, true);
15492
0
    }
15493
0
}
15494
15495
//-----------------------------------------------------------------------------
15496
// Docking: ImGuiDockContext Docking/Undocking functions
15497
//-----------------------------------------------------------------------------
15498
// - DockContextQueueDock()
15499
// - DockContextQueueUndockWindow()
15500
// - DockContextQueueUndockNode()
15501
// - DockContextQueueNotifyRemovedNode()
15502
// - DockContextProcessDock()
15503
// - DockContextProcessUndockWindow()
15504
// - DockContextProcessUndockNode()
15505
// - DockContextCalcDropPosForDocking()
15506
//-----------------------------------------------------------------------------
15507
15508
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15509
0
{
15510
0
    IM_ASSERT(target != payload);
15511
0
    ImGuiDockRequest req;
15512
0
    req.Type = ImGuiDockRequestType_Dock;
15513
0
    req.DockTargetWindow = target;
15514
0
    req.DockTargetNode = target_node;
15515
0
    req.DockPayload = payload;
15516
0
    req.DockSplitDir = split_dir;
15517
0
    req.DockSplitRatio = split_ratio;
15518
0
    req.DockSplitOuter = split_outer;
15519
0
    ctx->DockContext.Requests.push_back(req);
15520
0
}
15521
15522
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15523
0
{
15524
0
    ImGuiDockRequest req;
15525
0
    req.Type = ImGuiDockRequestType_Undock;
15526
0
    req.UndockTargetWindow = window;
15527
0
    ctx->DockContext.Requests.push_back(req);
15528
0
}
15529
15530
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15531
0
{
15532
0
    ImGuiDockRequest req;
15533
0
    req.Type = ImGuiDockRequestType_Undock;
15534
0
    req.UndockTargetNode = node;
15535
0
    ctx->DockContext.Requests.push_back(req);
15536
0
}
15537
15538
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15539
0
{
15540
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15541
0
    for (int n = 0; n < dc->Requests.Size; n++)
15542
0
        if (dc->Requests[n].DockTargetNode == node)
15543
0
            dc->Requests[n].Type = ImGuiDockRequestType_None;
15544
0
}
15545
15546
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15547
0
{
15548
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15549
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15550
15551
0
    ImGuiContext& g = *ctx;
15552
0
    IM_UNUSED(g);
15553
15554
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15555
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15556
0
    ImGuiDockNode* node = req->DockTargetNode;
15557
0
    if (payload_window)
15558
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15559
0
    else
15560
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15561
15562
    // Decide which Tab will be selected at the end of the operation
15563
0
    ImGuiID next_selected_id = 0;
15564
0
    ImGuiDockNode* payload_node = NULL;
15565
0
    if (payload_window)
15566
0
    {
15567
0
        payload_node = payload_window->DockNodeAsHost;
15568
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15569
0
        if (payload_node && payload_node->IsLeafNode())
15570
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15571
0
        if (payload_node == NULL)
15572
0
            next_selected_id = payload_window->TabId;
15573
0
    }
15574
15575
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15576
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15577
0
    if (node)
15578
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15579
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15580
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15581
15582
    // Create new node and add existing window to it
15583
0
    if (node == NULL)
15584
0
    {
15585
0
        node = DockContextAddNode(ctx, 0);
15586
0
        node->Pos = target_window->Pos;
15587
0
        node->Size = target_window->Size;
15588
0
        if (target_window->DockNodeAsHost == NULL)
15589
0
        {
15590
0
            DockNodeAddWindow(node, target_window, true);
15591
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15592
0
            target_window->DockIsActive = true;
15593
0
        }
15594
0
    }
15595
15596
0
    ImGuiDir split_dir = req->DockSplitDir;
15597
0
    if (split_dir != ImGuiDir_None)
15598
0
    {
15599
        // Split into two, one side will be our payload node unless we are dropping a loose window
15600
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15601
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15602
0
        const float split_ratio = req->DockSplitRatio;
15603
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15604
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15605
0
        new_node->HostWindow = node->HostWindow;
15606
0
        node = new_node;
15607
0
    }
15608
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15609
15610
0
    if (node != payload_node)
15611
0
    {
15612
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15613
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15614
0
        {
15615
0
            DockNodeAddTabBar(node);
15616
0
            for (int n = 0; n < node->Windows.Size; n++)
15617
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15618
0
        }
15619
15620
0
        if (payload_node != NULL)
15621
0
        {
15622
            // Transfer full payload node (with 1+ child windows or child nodes)
15623
0
            if (payload_node->IsSplitNode())
15624
0
            {
15625
0
                if (node->Windows.Size > 0)
15626
0
                {
15627
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15628
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15629
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15630
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15631
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15632
0
                    if (visible_node->TabBar)
15633
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15634
0
                    DockNodeMoveWindows(node, visible_node);
15635
0
                    DockNodeMoveWindows(visible_node, node);
15636
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15637
0
                }
15638
0
                if (node->IsCentralNode())
15639
0
                {
15640
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15641
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15642
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15643
0
                    IM_ASSERT(last_focused_node != NULL);
15644
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15645
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15646
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15647
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15648
0
                    last_focused_root_node->CentralNode = last_focused_node;
15649
0
                }
15650
15651
0
                IM_ASSERT(node->Windows.Size == 0);
15652
0
                DockNodeMoveChildNodes(node, payload_node);
15653
0
            }
15654
0
            else
15655
0
            {
15656
0
                const ImGuiID payload_dock_id = payload_node->ID;
15657
0
                DockNodeMoveWindows(node, payload_node);
15658
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15659
0
            }
15660
0
            DockContextRemoveNode(ctx, payload_node, true);
15661
0
        }
15662
0
        else if (payload_window)
15663
0
        {
15664
            // Transfer single window
15665
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15666
0
            node->VisibleWindow = payload_window;
15667
0
            DockNodeAddWindow(node, payload_window, true);
15668
0
            if (payload_dock_id != 0)
15669
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15670
0
        }
15671
0
    }
15672
0
    else
15673
0
    {
15674
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15675
0
        node->WantHiddenTabBarUpdate = true;
15676
0
    }
15677
15678
    // Update selection immediately
15679
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15680
0
        tab_bar->NextSelectedTabId = next_selected_id;
15681
0
    MarkIniSettingsDirty();
15682
0
}
15683
15684
// Problem:
15685
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15686
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15687
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15688
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15689
// Solution:
15690
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15691
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15692
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15693
0
{
15694
0
    if (ref_viewport == NULL)
15695
0
        return size;
15696
15697
0
    ImGuiContext& g = *GImGui;
15698
0
    ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f);
15699
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15700
0
    {
15701
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15702
0
        max_size = ImFloor(monitor->WorkSize * 0.90f);
15703
0
    }
15704
0
    return ImMin(size, max_size);
15705
0
}
15706
15707
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15708
0
{
15709
0
    ImGuiContext& g = *ctx;
15710
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15711
0
    if (window->DockNode)
15712
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15713
0
    else
15714
0
        window->DockId = 0;
15715
0
    window->Collapsed = false;
15716
0
    window->DockIsActive = false;
15717
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15718
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15719
15720
0
    MarkIniSettingsDirty();
15721
0
}
15722
15723
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15724
0
{
15725
0
    ImGuiContext& g = *ctx;
15726
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15727
0
    IM_ASSERT(node->IsLeafNode());
15728
0
    IM_ASSERT(node->Windows.Size >= 1);
15729
15730
0
    if (node->IsRootNode() || node->IsCentralNode())
15731
0
    {
15732
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15733
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15734
0
        new_node->Pos = node->Pos;
15735
0
        new_node->Size = node->Size;
15736
0
        new_node->SizeRef = node->SizeRef;
15737
0
        DockNodeMoveWindows(new_node, node);
15738
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15739
0
        node = new_node;
15740
0
    }
15741
0
    else
15742
0
    {
15743
        // Otherwise extract our node and merge our sibling back into the parent node.
15744
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15745
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15746
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15747
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15748
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15749
0
        node->ParentNode = NULL;
15750
0
    }
15751
0
    for (int n = 0; n < node->Windows.Size; n++)
15752
0
    {
15753
0
        ImGuiWindow* window = node->Windows[n];
15754
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15755
0
        if (window->ParentWindow)
15756
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15757
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15758
0
    }
15759
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15760
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15761
0
    node->WantMouseMove = true;
15762
0
    MarkIniSettingsDirty();
15763
0
}
15764
15765
// This is mostly used for automation.
15766
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15767
0
{
15768
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15769
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15770
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15771
0
        split_outer = true;
15772
0
    ImGuiDockPreviewData split_data;
15773
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15774
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15775
0
        return false;
15776
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15777
0
    return true;
15778
0
}
15779
15780
//-----------------------------------------------------------------------------
15781
// Docking: ImGuiDockNode
15782
//-----------------------------------------------------------------------------
15783
// - DockNodeGetTabOrder()
15784
// - DockNodeAddWindow()
15785
// - DockNodeRemoveWindow()
15786
// - DockNodeMoveChildNodes()
15787
// - DockNodeMoveWindows()
15788
// - DockNodeApplyPosSizeToWindows()
15789
// - DockNodeHideHostWindow()
15790
// - ImGuiDockNodeFindInfoResults
15791
// - DockNodeFindInfo()
15792
// - DockNodeFindWindowByID()
15793
// - DockNodeUpdateFlagsAndCollapse()
15794
// - DockNodeUpdateHasCentralNodeFlag()
15795
// - DockNodeUpdateVisibleFlag()
15796
// - DockNodeStartMouseMovingWindow()
15797
// - DockNodeUpdate()
15798
// - DockNodeUpdateWindowMenu()
15799
// - DockNodeBeginAmendTabBar()
15800
// - DockNodeEndAmendTabBar()
15801
// - DockNodeUpdateTabBar()
15802
// - DockNodeAddTabBar()
15803
// - DockNodeRemoveTabBar()
15804
// - DockNodeIsDropAllowedOne()
15805
// - DockNodeIsDropAllowed()
15806
// - DockNodeCalcTabBarLayout()
15807
// - DockNodeCalcSplitRects()
15808
// - DockNodeCalcDropRectsAndTestMousePos()
15809
// - DockNodePreviewDockSetup()
15810
// - DockNodePreviewDockRender()
15811
//-----------------------------------------------------------------------------
15812
15813
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
15814
0
{
15815
0
    ID = id;
15816
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
15817
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
15818
0
    TabBar = NULL;
15819
0
    SplitAxis = ImGuiAxis_None;
15820
15821
0
    State = ImGuiDockNodeState_Unknown;
15822
0
    LastBgColor = IM_COL32_WHITE;
15823
0
    HostWindow = VisibleWindow = NULL;
15824
0
    CentralNode = OnlyNodeWithWindows = NULL;
15825
0
    CountNodeWithWindows = 0;
15826
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
15827
0
    LastFocusedNodeId = 0;
15828
0
    SelectedTabId = 0;
15829
0
    WantCloseTabId = 0;
15830
0
    RefViewportId = 0;
15831
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
15832
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
15833
0
    IsVisible = true;
15834
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
15835
0
    IsBgDrawnThisFrame = false;
15836
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
15837
0
}
15838
15839
ImGuiDockNode::~ImGuiDockNode()
15840
0
{
15841
0
    IM_DELETE(TabBar);
15842
0
    TabBar = NULL;
15843
0
    ChildNodes[0] = ChildNodes[1] = NULL;
15844
0
}
15845
15846
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
15847
0
{
15848
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
15849
0
    if (tab_bar == NULL)
15850
0
        return -1;
15851
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
15852
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
15853
0
}
15854
15855
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
15856
0
{
15857
0
    window->Hidden = true;
15858
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
15859
0
}
15860
15861
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
15862
0
{
15863
0
    ImGuiContext& g = *GImGui; (void)g;
15864
0
    if (window->DockNode)
15865
0
    {
15866
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
15867
0
        IM_ASSERT(window->DockNode->ID != node->ID);
15868
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
15869
0
    }
15870
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
15871
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15872
15873
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
15874
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
15875
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
15876
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
15877
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
15878
15879
0
    node->Windows.push_back(window);
15880
0
    node->WantHiddenTabBarUpdate = true;
15881
0
    window->DockNode = node;
15882
0
    window->DockId = node->ID;
15883
0
    window->DockIsActive = (node->Windows.Size > 1);
15884
0
    window->DockTabWantClose = false;
15885
15886
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
15887
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
15888
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
15889
0
    {
15890
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
15891
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
15892
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
15893
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
15894
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
15895
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
15896
0
    }
15897
15898
    // Add to tab bar if requested
15899
0
    if (add_to_tab_bar)
15900
0
    {
15901
0
        if (node->TabBar == NULL)
15902
0
        {
15903
0
            DockNodeAddTabBar(node);
15904
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
15905
15906
            // Add existing windows
15907
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
15908
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15909
0
        }
15910
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
15911
0
    }
15912
15913
0
    DockNodeUpdateVisibleFlag(node);
15914
15915
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
15916
0
    if (node->HostWindow)
15917
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
15918
0
}
15919
15920
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
15921
0
{
15922
0
    ImGuiContext& g = *GImGui;
15923
0
    IM_ASSERT(window->DockNode == node);
15924
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
15925
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
15926
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
15927
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15928
15929
0
    window->DockNode = NULL;
15930
0
    window->DockIsActive = window->DockTabWantClose = false;
15931
0
    window->DockId = save_dock_id;
15932
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15933
0
    if (window->ParentWindow)
15934
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
15935
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
15936
15937
0
    if (node->HostWindow && node->HostWindow->ViewportOwned)
15938
0
    {
15939
        // When undocking from a user interaction this will always run in NewFrame() and have not much effect.
15940
        // But mid-frame, if we clear viewport we need to mark window as hidden as well.
15941
0
        window->Viewport = NULL;
15942
0
        window->ViewportId = 0;
15943
0
        window->ViewportOwned = false;
15944
0
        window->Hidden = true;
15945
0
    }
15946
15947
    // Remove window
15948
0
    bool erased = false;
15949
0
    for (int n = 0; n < node->Windows.Size; n++)
15950
0
        if (node->Windows[n] == window)
15951
0
        {
15952
0
            node->Windows.erase(node->Windows.Data + n);
15953
0
            erased = true;
15954
0
            break;
15955
0
        }
15956
0
    if (!erased)
15957
0
        IM_ASSERT(erased);
15958
0
    if (node->VisibleWindow == window)
15959
0
        node->VisibleWindow = NULL;
15960
15961
    // Remove tab and possibly tab bar
15962
0
    node->WantHiddenTabBarUpdate = true;
15963
0
    if (node->TabBar)
15964
0
    {
15965
0
        TabBarRemoveTab(node->TabBar, window->TabId);
15966
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
15967
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
15968
0
            DockNodeRemoveTabBar(node);
15969
0
    }
15970
15971
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
15972
0
    {
15973
        // Automatic dock node delete themselves if they are not holding at least one tab
15974
0
        DockContextRemoveNode(&g, node, true);
15975
0
        return;
15976
0
    }
15977
15978
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
15979
0
    {
15980
0
        ImGuiWindow* remaining_window = node->Windows[0];
15981
        // Note: we used to transport viewport ownership here.
15982
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
15983
0
    }
15984
15985
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
15986
0
    DockNodeUpdateVisibleFlag(node);
15987
0
}
15988
15989
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15990
0
{
15991
0
    IM_ASSERT(dst_node->Windows.Size == 0);
15992
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
15993
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
15994
0
    if (dst_node->ChildNodes[0])
15995
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
15996
0
    if (dst_node->ChildNodes[1])
15997
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
15998
0
    dst_node->SplitAxis = src_node->SplitAxis;
15999
0
    dst_node->SizeRef = src_node->SizeRef;
16000
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
16001
0
}
16002
16003
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
16004
0
{
16005
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
16006
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
16007
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
16008
0
    if (src_tab_bar != NULL)
16009
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
16010
16011
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
16012
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
16013
0
    if (move_tab_bar)
16014
0
    {
16015
0
        dst_node->TabBar = src_node->TabBar;
16016
0
        src_node->TabBar = NULL;
16017
0
    }
16018
16019
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
16020
0
    for (ImGuiWindow* window : src_node->Windows)
16021
0
    {
16022
0
        window->DockNode = NULL;
16023
0
        window->DockIsActive = false;
16024
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
16025
0
    }
16026
0
    src_node->Windows.clear();
16027
16028
0
    if (!move_tab_bar && src_node->TabBar)
16029
0
    {
16030
0
        if (dst_node->TabBar)
16031
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
16032
0
        DockNodeRemoveTabBar(src_node);
16033
0
    }
16034
0
}
16035
16036
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
16037
0
{
16038
0
    for (int n = 0; n < node->Windows.Size; n++)
16039
0
    {
16040
0
        SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
16041
0
        SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
16042
0
    }
16043
0
}
16044
16045
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
16046
0
{
16047
0
    if (node->HostWindow)
16048
0
    {
16049
0
        if (node->HostWindow->DockNodeAsHost == node)
16050
0
            node->HostWindow->DockNodeAsHost = NULL;
16051
0
        node->HostWindow = NULL;
16052
0
    }
16053
16054
0
    if (node->Windows.Size == 1)
16055
0
    {
16056
0
        node->VisibleWindow = node->Windows[0];
16057
0
        node->Windows[0]->DockIsActive = false;
16058
0
    }
16059
16060
0
    if (node->TabBar)
16061
0
        DockNodeRemoveTabBar(node);
16062
0
}
16063
16064
// Search function called once by root node in DockNodeUpdate()
16065
struct ImGuiDockNodeTreeInfo
16066
{
16067
    ImGuiDockNode*      CentralNode;
16068
    ImGuiDockNode*      FirstNodeWithWindows;
16069
    int                 CountNodesWithWindows;
16070
    //ImGuiWindowClass  WindowClassForMerges;
16071
16072
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
16073
};
16074
16075
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
16076
0
{
16077
0
    if (node->Windows.Size > 0)
16078
0
    {
16079
0
        if (info->FirstNodeWithWindows == NULL)
16080
0
            info->FirstNodeWithWindows = node;
16081
0
        info->CountNodesWithWindows++;
16082
0
    }
16083
0
    if (node->IsCentralNode())
16084
0
    {
16085
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
16086
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
16087
0
        info->CentralNode = node;
16088
0
    }
16089
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
16090
0
        return;
16091
0
    if (node->ChildNodes[0])
16092
0
        DockNodeFindInfo(node->ChildNodes[0], info);
16093
0
    if (node->ChildNodes[1])
16094
0
        DockNodeFindInfo(node->ChildNodes[1], info);
16095
0
}
16096
16097
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
16098
0
{
16099
0
    IM_ASSERT(id != 0);
16100
0
    for (int n = 0; n < node->Windows.Size; n++)
16101
0
        if (node->Windows[n]->ID == id)
16102
0
            return node->Windows[n];
16103
0
    return NULL;
16104
0
}
16105
16106
// - Remove inactive windows/nodes.
16107
// - Update visibility flag.
16108
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
16109
0
{
16110
0
    ImGuiContext& g = *GImGui;
16111
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
16112
16113
    // Inherit most flags
16114
0
    if (node->ParentNode)
16115
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16116
16117
    // Recurse into children
16118
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
16119
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
16120
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
16121
0
    node->HasCentralNodeChild = false;
16122
0
    if (node->ChildNodes[0])
16123
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
16124
0
    if (node->ChildNodes[1])
16125
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
16126
16127
    // Remove inactive windows, collapse nodes
16128
    // Merge node flags overrides stored in windows
16129
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
16130
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16131
0
    {
16132
0
        ImGuiWindow* window = node->Windows[window_n];
16133
0
        IM_ASSERT(window->DockNode == node);
16134
16135
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16136
0
        bool remove = false;
16137
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
16138
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
16139
0
        remove |= (window->DockTabWantClose);
16140
0
        if (remove)
16141
0
        {
16142
0
            window->DockTabWantClose = false;
16143
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
16144
0
            {
16145
0
                DockNodeHideHostWindow(node);
16146
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16147
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
16148
0
                return;
16149
0
            }
16150
0
            DockNodeRemoveWindow(node, window, node->ID);
16151
0
            window_n--;
16152
0
            continue;
16153
0
        }
16154
16155
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
16156
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
16157
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
16158
0
    }
16159
0
    node->UpdateMergedFlags();
16160
16161
    // Auto-hide tab bar option
16162
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
16163
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
16164
0
        node->WantHiddenTabBarToggle = true;
16165
0
    node->WantHiddenTabBarUpdate = false;
16166
16167
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
16168
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
16169
0
        node->WantHiddenTabBarToggle = false;
16170
16171
    // Apply toggles at a single point of the frame (here!)
16172
0
    if (node->Windows.Size > 1)
16173
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
16174
0
    else if (node->WantHiddenTabBarToggle)
16175
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
16176
0
    node->WantHiddenTabBarToggle = false;
16177
16178
0
    DockNodeUpdateVisibleFlag(node);
16179
0
}
16180
16181
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
16182
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
16183
0
{
16184
0
    node->HasCentralNodeChild = false;
16185
0
    if (node->ChildNodes[0])
16186
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
16187
0
    if (node->ChildNodes[1])
16188
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
16189
0
    if (node->IsRootNode())
16190
0
    {
16191
0
        ImGuiDockNode* mark_node = node->CentralNode;
16192
0
        while (mark_node)
16193
0
        {
16194
0
            mark_node->HasCentralNodeChild = true;
16195
0
            mark_node = mark_node->ParentNode;
16196
0
        }
16197
0
    }
16198
0
}
16199
16200
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
16201
0
{
16202
    // Update visibility flag
16203
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
16204
0
    is_visible |= (node->Windows.Size > 0);
16205
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
16206
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
16207
0
    node->IsVisible = is_visible;
16208
0
}
16209
16210
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
16211
0
{
16212
0
    ImGuiContext& g = *GImGui;
16213
0
    IM_ASSERT(node->WantMouseMove == true);
16214
0
    StartMouseMovingWindow(window);
16215
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
16216
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
16217
0
    node->WantMouseMove = false;
16218
0
}
16219
16220
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
16221
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
16222
0
{
16223
0
    DockNodeUpdateFlagsAndCollapse(node);
16224
16225
    // - Setup central node pointers
16226
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
16227
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
16228
0
    ImGuiDockNodeTreeInfo info;
16229
0
    DockNodeFindInfo(node, &info);
16230
0
    node->CentralNode = info.CentralNode;
16231
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
16232
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
16233
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
16234
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
16235
16236
    // Copy the window class from of our first window so it can be used for proper dock filtering.
16237
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
16238
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
16239
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
16240
0
    {
16241
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
16242
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
16243
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
16244
0
            {
16245
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
16246
0
                break;
16247
0
            }
16248
0
    }
16249
16250
0
    ImGuiDockNode* mark_node = node->CentralNode;
16251
0
    while (mark_node)
16252
0
    {
16253
0
        mark_node->HasCentralNodeChild = true;
16254
0
        mark_node = mark_node->ParentNode;
16255
0
    }
16256
0
}
16257
16258
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
16259
0
{
16260
    // Remove ourselves from any previous different host window
16261
    // This can happen if a user mistakenly does (see #4295 for details):
16262
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
16263
    //  - N+1: NewFrame()                   // will create floating host window for that node
16264
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
16265
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
16266
0
        node->HostWindow->DockNodeAsHost = NULL;
16267
16268
0
    host_window->DockNodeAsHost = node;
16269
0
    node->HostWindow = host_window;
16270
0
}
16271
16272
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
16273
0
{
16274
0
    ImGuiContext& g = *GImGui;
16275
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
16276
0
    node->LastFrameAlive = g.FrameCount;
16277
0
    node->IsBgDrawnThisFrame = false;
16278
16279
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
16280
0
    if (node->IsRootNode())
16281
0
        DockNodeUpdateForRootNode(node);
16282
16283
    // Remove tab bar if not needed
16284
0
    if (node->TabBar && node->IsNoTabBar())
16285
0
        DockNodeRemoveTabBar(node);
16286
16287
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
16288
0
    bool want_to_hide_host_window = false;
16289
0
    if (node->IsFloatingNode())
16290
0
    {
16291
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
16292
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
16293
0
                want_to_hide_host_window = true;
16294
0
        if (node->CountNodeWithWindows == 0)
16295
0
            want_to_hide_host_window = true;
16296
0
    }
16297
0
    if (want_to_hide_host_window)
16298
0
    {
16299
0
        if (node->Windows.Size == 1)
16300
0
        {
16301
            // Floating window pos/size is authoritative
16302
0
            ImGuiWindow* single_window = node->Windows[0];
16303
0
            node->Pos = single_window->Pos;
16304
0
            node->Size = single_window->SizeFull;
16305
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
16306
16307
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
16308
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
16309
0
                FocusWindow(single_window);
16310
0
            if (node->HostWindow)
16311
0
            {
16312
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X->%08X to Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, single_window->ID, single_window->Name);
16313
0
                single_window->Viewport = node->HostWindow->Viewport;
16314
0
                single_window->ViewportId = node->HostWindow->ViewportId;
16315
0
                if (node->HostWindow->ViewportOwned)
16316
0
                {
16317
0
                    single_window->Viewport->ID = single_window->ID;
16318
0
                    single_window->Viewport->Window = single_window;
16319
0
                    single_window->ViewportOwned = true;
16320
0
                }
16321
0
            }
16322
0
            node->RefViewportId = single_window->ViewportId;
16323
0
        }
16324
16325
0
        DockNodeHideHostWindow(node);
16326
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
16327
0
        node->WantCloseAll = false;
16328
0
        node->WantCloseTabId = 0;
16329
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
16330
0
        node->LastFrameActive = g.FrameCount;
16331
16332
0
        if (node->WantMouseMove && node->Windows.Size == 1)
16333
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
16334
0
        return;
16335
0
    }
16336
16337
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
16338
    // while the expected visible window is resizing itself.
16339
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
16340
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
16341
    //   N+0: Begin(): window created (with no known size), node is created
16342
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
16343
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
16344
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
16345
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
16346
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
16347
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
16348
0
    {
16349
0
        IM_ASSERT(node->Windows.Size > 0);
16350
0
        ImGuiWindow* ref_window = NULL;
16351
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
16352
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
16353
0
        if (ref_window == NULL)
16354
0
            ref_window = node->Windows[0];
16355
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
16356
0
        {
16357
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
16358
0
            return;
16359
0
        }
16360
0
    }
16361
16362
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16363
16364
    // Decide if the node will have a close button and a window menu button
16365
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
16366
0
    node->HasCloseButton = false;
16367
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16368
0
    {
16369
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
16370
0
        ImGuiWindow* window = node->Windows[window_n];
16371
0
        node->HasCloseButton |= window->HasCloseButton;
16372
0
        window->DockIsActive = (node->Windows.Size > 1);
16373
0
    }
16374
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
16375
0
        node->HasCloseButton = false;
16376
16377
    // Bind or create host window
16378
0
    ImGuiWindow* host_window = NULL;
16379
0
    bool beginned_into_host_window = false;
16380
0
    if (node->IsDockSpace())
16381
0
    {
16382
        // [Explicit root dockspace node]
16383
0
        IM_ASSERT(node->HostWindow);
16384
0
        host_window = node->HostWindow;
16385
0
    }
16386
0
    else
16387
0
    {
16388
        // [Automatic root or child nodes]
16389
0
        if (node->IsRootNode() && node->IsVisible)
16390
0
        {
16391
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16392
16393
            // Sync Pos
16394
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
16395
0
                SetNextWindowPos(ref_window->Pos);
16396
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
16397
0
                SetNextWindowPos(node->Pos);
16398
16399
            // Sync Size
16400
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16401
0
                SetNextWindowSize(ref_window->SizeFull);
16402
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
16403
0
                SetNextWindowSize(node->Size);
16404
16405
            // Sync Collapsed
16406
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
16407
0
                SetNextWindowCollapsed(ref_window->Collapsed);
16408
16409
            // Sync Viewport
16410
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
16411
0
                SetNextWindowViewport(ref_window->ViewportId);
16412
0
            else if (node->AuthorityForViewport == ImGuiDataAuthority_Window && node->RefViewportId != 0)
16413
0
                SetNextWindowViewport(node->RefViewportId);
16414
16415
0
            SetNextWindowClass(&node->WindowClass);
16416
16417
            // Begin into the host window
16418
0
            char window_label[20];
16419
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
16420
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
16421
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
16422
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
16423
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
16424
16425
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
16426
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
16427
0
            Begin(window_label, NULL, window_flags);
16428
0
            PopStyleVar();
16429
0
            beginned_into_host_window = true;
16430
16431
0
            host_window = g.CurrentWindow;
16432
0
            DockNodeSetupHostWindow(node, host_window);
16433
0
            host_window->DC.CursorPos = host_window->Pos;
16434
0
            node->Pos = host_window->Pos;
16435
0
            node->Size = host_window->Size;
16436
16437
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
16438
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
16439
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
16440
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
16441
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
16442
            // after the dock host window, losing their top-most status.
16443
0
            if (node->HostWindow->Appearing)
16444
0
                BringWindowToDisplayFront(node->HostWindow);
16445
16446
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16447
0
        }
16448
0
        else if (node->ParentNode)
16449
0
        {
16450
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
16451
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16452
0
        }
16453
0
        if (node->WantMouseMove && node->HostWindow)
16454
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
16455
0
    }
16456
0
    node->RefViewportId = 0; // Clear when we have a host window
16457
16458
    // Update focused node (the one whose title bar is highlight) within a node tree
16459
0
    if (node->IsSplitNode())
16460
0
        IM_ASSERT(node->TabBar == NULL);
16461
0
    if (node->IsRootNode())
16462
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
16463
0
            while (p_window != NULL && p_window->DockNode != NULL)
16464
0
            {
16465
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
16466
0
                if (p_node == node)
16467
0
                {
16468
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
16469
0
                    break;
16470
0
                }
16471
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
16472
0
            }
16473
16474
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
16475
0
    ImGuiDockNode* central_node = node->CentralNode;
16476
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
16477
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
16478
0
    if (central_node_hole)
16479
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
16480
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
16481
0
                central_node_hole_register_hit_test_hole = false;
16482
0
    if (central_node_hole_register_hit_test_hole)
16483
0
    {
16484
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
16485
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
16486
        // covering passthru node we'd have a gap on the edge not covered by the hole)
16487
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
16488
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
16489
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
16490
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
16491
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
16492
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
16493
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
16494
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
16495
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
16496
0
        if (central_node_hole && !hole_rect.IsInverted())
16497
0
        {
16498
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16499
0
            if (host_window->ParentWindow)
16500
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16501
0
        }
16502
0
    }
16503
16504
    // Update position/size, process and draw resizing splitters
16505
0
    if (node->IsRootNode() && host_window)
16506
0
    {
16507
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
16508
0
        DockNodeTreeUpdateSplitter(node);
16509
0
    }
16510
16511
    // Draw empty node background (currently can only be the Central Node)
16512
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16513
0
    {
16514
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16515
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16516
0
        if (node->LastBgColor != 0)
16517
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16518
0
        node->IsBgDrawnThisFrame = true;
16519
0
    }
16520
16521
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16522
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16523
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16524
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16525
0
    if (render_dockspace_bg && node->IsVisible)
16526
0
    {
16527
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16528
0
        if (central_node_hole)
16529
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16530
0
        else
16531
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16532
0
    }
16533
16534
    // Draw and populate Tab Bar
16535
0
    if (host_window)
16536
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16537
0
    if (host_window && node->Windows.Size > 0)
16538
0
    {
16539
0
        DockNodeUpdateTabBar(node, host_window);
16540
0
    }
16541
0
    else
16542
0
    {
16543
0
        node->WantCloseAll = false;
16544
0
        node->WantCloseTabId = 0;
16545
0
        node->IsFocused = false;
16546
0
    }
16547
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16548
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16549
0
    else if (node->Windows.Size > 0)
16550
0
        node->SelectedTabId = node->Windows[0]->TabId;
16551
16552
    // Draw payload drop target
16553
0
    if (host_window && node->IsVisible)
16554
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16555
0
            BeginDockableDragDropTarget(host_window);
16556
16557
    // We update this after DockNodeUpdateTabBar()
16558
0
    node->LastFrameActive = g.FrameCount;
16559
16560
    // Recurse into children
16561
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16562
0
    if (host_window)
16563
0
    {
16564
0
        if (node->ChildNodes[0])
16565
0
            DockNodeUpdate(node->ChildNodes[0]);
16566
0
        if (node->ChildNodes[1])
16567
0
            DockNodeUpdate(node->ChildNodes[1]);
16568
16569
        // Render outer borders last (after the tab bar)
16570
0
        if (node->IsRootNode())
16571
0
            RenderWindowOuterBorders(host_window);
16572
0
    }
16573
16574
    // End host window
16575
0
    if (beginned_into_host_window) //-V1020
16576
0
        End();
16577
0
}
16578
16579
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16580
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16581
0
{
16582
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16583
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16584
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16585
0
        return d;
16586
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16587
0
}
16588
16589
// Default handler for g.DockNodeWindowMenuHandler(): display the list of windows for a given dock-node.
16590
// This is exceptionally stored in a function pointer to also user applications to tweak this menu (undocumented)
16591
// Custom overrides may want to decorate, group, sort entries.
16592
// Please note those are internal structures: if you copy this expect occasional breakage.
16593
void ImGui::DockNodeWindowMenuHandler_Default(ImGuiContext* ctx, ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16594
0
{
16595
0
    IM_UNUSED(ctx);
16596
0
    if (tab_bar->Tabs.Size == 1)
16597
0
    {
16598
        // "Hide tab bar" option. Being one of our rare user-facing string we pull it from a table.
16599
0
        if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16600
0
            node->WantHiddenTabBarToggle = true;
16601
0
    }
16602
0
    else
16603
0
    {
16604
        // Display a selectable list of windows in this docking node
16605
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16606
0
        {
16607
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16608
0
            if (tab->Flags & ImGuiTabItemFlags_Button)
16609
0
                continue;
16610
0
            if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16611
0
                TabBarQueueFocus(tab_bar, tab);
16612
0
            SameLine();
16613
0
            Text("   ");
16614
0
        }
16615
0
    }
16616
0
}
16617
16618
static void ImGui::DockNodeWindowMenuUpdate(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16619
0
{
16620
    // Try to position the menu so it is more likely to stays within the same viewport
16621
0
    ImGuiContext& g = *GImGui;
16622
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16623
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16624
0
    else
16625
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16626
0
    if (BeginPopup("#WindowMenu"))
16627
0
    {
16628
0
        node->IsFocused = true;
16629
0
        g.DockNodeWindowMenuHandler(&g, node, tab_bar);
16630
0
        EndPopup();
16631
0
    }
16632
0
}
16633
16634
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16635
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16636
0
{
16637
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16638
0
        return false;
16639
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16640
0
        return false;
16641
0
    Begin(node->HostWindow->Name);
16642
0
    PushOverrideID(node->ID);
16643
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node);
16644
0
    IM_UNUSED(ret);
16645
0
    IM_ASSERT(ret);
16646
0
    return true;
16647
0
}
16648
16649
void ImGui::DockNodeEndAmendTabBar()
16650
0
{
16651
0
    EndTabBar();
16652
0
    PopID();
16653
0
    End();
16654
0
}
16655
16656
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16657
0
{
16658
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16659
0
    ImGuiContext& g = *GImGui;
16660
0
    if (g.NavWindowingTarget)
16661
0
        return (g.NavWindowingTarget->DockNode == node);
16662
16663
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16664
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16665
0
    {
16666
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16667
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16668
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16669
0
            parent_window = parent_window->ParentWindow->RootWindow;
16670
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16671
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16672
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16673
0
                return true;
16674
0
    }
16675
0
    return false;
16676
0
}
16677
16678
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16679
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16680
0
{
16681
0
    ImGuiContext& g = *GImGui;
16682
0
    ImGuiStyle& style = g.Style;
16683
16684
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16685
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16686
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16687
0
    node->WantCloseAll = false;
16688
0
    node->WantCloseTabId = 0;
16689
16690
    // Decide if we should use a focused title bar color
16691
0
    bool is_focused = false;
16692
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16693
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16694
0
        is_focused = true;
16695
16696
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16697
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16698
0
    {
16699
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16700
0
        node->IsFocused = is_focused;
16701
0
        if (is_focused)
16702
0
            node->LastFrameFocused = g.FrameCount;
16703
0
        if (node->VisibleWindow)
16704
0
        {
16705
            // Notify root of visible window (used to display title in OS task bar)
16706
0
            if (is_focused || root_node->VisibleWindow == NULL)
16707
0
                root_node->VisibleWindow = node->VisibleWindow;
16708
0
            if (node->TabBar)
16709
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16710
0
        }
16711
0
        return;
16712
0
    }
16713
16714
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16715
0
    bool backup_skip_item = host_window->SkipItems;
16716
0
    if (!node->IsDockSpace())
16717
0
    {
16718
0
        host_window->SkipItems = false;
16719
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16720
0
    }
16721
16722
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16723
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16724
    // as docked windows themselves will override the stack with their own root ID.
16725
0
    PushOverrideID(node->ID);
16726
0
    ImGuiTabBar* tab_bar = node->TabBar;
16727
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16728
0
    if (tab_bar == NULL)
16729
0
    {
16730
0
        DockNodeAddTabBar(node);
16731
0
        tab_bar = node->TabBar;
16732
0
    }
16733
16734
0
    ImGuiID focus_tab_id = 0;
16735
0
    node->IsFocused = is_focused;
16736
16737
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16738
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16739
16740
    // In a dock node, the Collapse Button turns into the Window Menu button.
16741
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16742
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16743
0
    {
16744
0
        ImGuiID next_selected_tab_id = tab_bar->NextSelectedTabId;
16745
0
        DockNodeWindowMenuUpdate(node, tab_bar);
16746
0
        if (tab_bar->NextSelectedTabId != 0 && tab_bar->NextSelectedTabId != next_selected_tab_id)
16747
0
            focus_tab_id = tab_bar->NextSelectedTabId;
16748
0
        is_focused |= node->IsFocused;
16749
0
    }
16750
16751
    // Layout
16752
0
    ImRect title_bar_rect, tab_bar_rect;
16753
0
    ImVec2 window_menu_button_pos;
16754
0
    ImVec2 close_button_pos;
16755
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16756
16757
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16758
0
    const int tabs_count_old = tab_bar->Tabs.Size;
16759
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16760
0
    {
16761
0
        ImGuiWindow* window = node->Windows[window_n];
16762
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16763
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16764
0
    }
16765
16766
    // Title bar
16767
0
    if (is_focused)
16768
0
        node->LastFrameFocused = g.FrameCount;
16769
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16770
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE);
16771
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
16772
16773
    // Docking/Collapse button
16774
0
    if (has_window_menu_button)
16775
0
    {
16776
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
16777
0
            OpenPopup("#WindowMenu");
16778
0
        if (IsItemActive())
16779
0
            focus_tab_id = tab_bar->SelectedTabId;
16780
0
    }
16781
16782
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
16783
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
16784
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
16785
0
    {
16786
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
16787
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
16788
0
        tabs_unsorted_start = tab_n;
16789
0
    }
16790
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
16791
0
    {
16792
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
16793
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
16794
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
16795
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
16796
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
16797
0
    }
16798
16799
    // Apply NavWindow focus back to the tab bar
16800
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
16801
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
16802
16803
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
16804
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
16805
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
16806
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
16807
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
16808
16809
    // Begin tab bar
16810
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
16811
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
16812
0
    if (!host_window->Collapsed && is_focused)
16813
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
16814
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
16815
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
16816
16817
    // Backup style colors
16818
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
16819
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16820
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
16821
16822
    // Submit actual tabs
16823
0
    node->VisibleWindow = NULL;
16824
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16825
0
    {
16826
0
        ImGuiWindow* window = node->Windows[window_n];
16827
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
16828
0
            continue;
16829
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
16830
0
        {
16831
0
            ImGuiTabItemFlags tab_item_flags = 0;
16832
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
16833
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
16834
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
16835
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
16836
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
16837
16838
            // Apply stored style overrides for the window
16839
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16840
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
16841
16842
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
16843
0
            bool tab_open = true;
16844
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
16845
0
            if (!tab_open)
16846
0
                node->WantCloseTabId = window->TabId;
16847
0
            if (tab_bar->VisibleTabId == window->TabId)
16848
0
                node->VisibleWindow = window;
16849
16850
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
16851
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
16852
0
            window->DockTabItemRect = g.LastItemData.Rect;
16853
16854
            // Update navigation ID on menu layer
16855
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
16856
0
                host_window->NavLastIds[1] = window->TabId;
16857
0
        }
16858
0
    }
16859
16860
    // Restore style colors
16861
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16862
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
16863
16864
    // Notify root of visible window (used to display title in OS task bar)
16865
0
    if (node->VisibleWindow)
16866
0
        if (is_focused || root_node->VisibleWindow == NULL)
16867
0
            root_node->VisibleWindow = node->VisibleWindow;
16868
16869
    // Close button (after VisibleWindow was updated)
16870
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
16871
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
16872
0
    const bool close_button_is_visible = node->HasCloseButton;
16873
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
16874
0
    if (close_button_is_visible)
16875
0
    {
16876
0
        if (!close_button_is_enabled)
16877
0
        {
16878
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
16879
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
16880
0
        }
16881
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
16882
0
        {
16883
0
            node->WantCloseAll = true;
16884
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
16885
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
16886
0
        }
16887
        //if (IsItemActive())
16888
        //    focus_tab_id = tab_bar->SelectedTabId;
16889
0
        if (!close_button_is_enabled)
16890
0
        {
16891
0
            PopStyleColor();
16892
0
            PopItemFlag();
16893
0
        }
16894
0
    }
16895
16896
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
16897
    // FIXME: TabItems submitted earlier use AllowItemOverlap so we manually perform a more specific test for now (hovered || held) in order to not cover them.
16898
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
16899
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
16900
0
    {
16901
        // AllowItem mode required for appending into dock node tab bar,
16902
        // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
16903
0
        bool held;
16904
0
        KeepAliveID(title_bar_id);
16905
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowOverlap);
16906
0
        if (g.HoveredId == title_bar_id)
16907
0
        {
16908
0
            g.LastItemData.ID = title_bar_id;
16909
0
        }
16910
0
        if (held)
16911
0
        {
16912
0
            if (IsMouseClicked(0))
16913
0
                focus_tab_id = tab_bar->SelectedTabId;
16914
16915
            // Forward moving request to selected window
16916
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
16917
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
16918
0
        }
16919
0
    }
16920
16921
    // Forward focus from host node to selected window
16922
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
16923
    //    focus_tab_id = tab_bar->SelectedTabId;
16924
16925
    // When clicked on a tab we requested focus to the docked child
16926
    // This overrides the value set by "forward focus from host node to selected window".
16927
0
    if (tab_bar->NextSelectedTabId)
16928
0
        focus_tab_id = tab_bar->NextSelectedTabId;
16929
16930
    // Apply navigation focus
16931
0
    if (focus_tab_id != 0)
16932
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
16933
0
            if (tab->Window)
16934
0
            {
16935
0
                FocusWindow(tab->Window);
16936
0
                NavInitWindow(tab->Window, false);
16937
0
            }
16938
16939
0
    EndTabBar();
16940
0
    PopID();
16941
16942
    // Restore SkipItems flag
16943
0
    if (!node->IsDockSpace())
16944
0
    {
16945
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
16946
0
        host_window->SkipItems = backup_skip_item;
16947
0
    }
16948
0
}
16949
16950
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
16951
0
{
16952
0
    IM_ASSERT(node->TabBar == NULL);
16953
0
    node->TabBar = IM_NEW(ImGuiTabBar);
16954
0
}
16955
16956
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
16957
0
{
16958
0
    if (node->TabBar == NULL)
16959
0
        return;
16960
0
    IM_DELETE(node->TabBar);
16961
0
    node->TabBar = NULL;
16962
0
}
16963
16964
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
16965
0
{
16966
0
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
16967
0
        return false;
16968
16969
0
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
16970
0
    ImGuiWindowClass* payload_class = &payload->WindowClass;
16971
0
    if (host_class->ClassId != payload_class->ClassId)
16972
0
    {
16973
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
16974
0
            return true;
16975
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
16976
0
            return true;
16977
0
        return false;
16978
0
    }
16979
16980
    // Prevent docking any window created above a popup
16981
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
16982
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
16983
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
16984
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
16985
0
    ImGuiContext& g = *GImGui;
16986
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
16987
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
16988
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
16989
0
                return false;
16990
16991
0
    return true;
16992
0
}
16993
16994
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
16995
0
{
16996
0
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
16997
0
        return true;
16998
16999
0
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
17000
0
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
17001
0
    {
17002
0
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
17003
0
        if (DockNodeIsDropAllowedOne(payload, host_window))
17004
0
            return true;
17005
0
    }
17006
0
    return false;
17007
0
}
17008
17009
// window menu button == collapse button when not in a dock node.
17010
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
17011
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
17012
0
{
17013
0
    ImGuiContext& g = *GImGui;
17014
0
    ImGuiStyle& style = g.Style;
17015
17016
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
17017
0
    if (out_title_rect) { *out_title_rect = r; }
17018
17019
0
    r.Min.x += style.WindowBorderSize;
17020
0
    r.Max.x -= style.WindowBorderSize;
17021
17022
0
    float button_sz = g.FontSize;
17023
17024
0
    ImVec2 window_menu_button_pos = r.Min;
17025
0
    r.Min.x += style.FramePadding.x;
17026
0
    r.Max.x -= style.FramePadding.x;
17027
0
    if (node->HasCloseButton)
17028
0
    {
17029
0
        r.Max.x -= button_sz;
17030
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y);
17031
0
    }
17032
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
17033
0
    {
17034
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
17035
0
    }
17036
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
17037
0
    {
17038
0
        r.Max.x -= button_sz + style.FramePadding.x;
17039
0
        window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
17040
0
    }
17041
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
17042
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
17043
0
}
17044
17045
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
17046
0
{
17047
0
    ImGuiContext& g = *GImGui;
17048
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
17049
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17050
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
17051
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
17052
17053
    // Distribute size on given axis (with a desired size or equally)
17054
0
    const float w_avail = size_old[axis] - dock_spacing;
17055
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
17056
0
    {
17057
0
        size_new[axis] = size_new_desired[axis];
17058
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
17059
0
    }
17060
0
    else
17061
0
    {
17062
0
        size_new[axis] = IM_FLOOR(w_avail * 0.5f);
17063
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
17064
0
    }
17065
17066
    // Position each node
17067
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
17068
0
    {
17069
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
17070
0
    }
17071
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
17072
0
    {
17073
0
        pos_new[axis] = pos_old[axis];
17074
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
17075
0
    }
17076
0
}
17077
17078
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
17079
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
17080
0
{
17081
0
    ImGuiContext& g = *GImGui;
17082
17083
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
17084
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
17085
0
    float hs_w; // Half-size, longer axis
17086
0
    float hs_h; // Half-size, smaller axis
17087
0
    ImVec2 off; // Distance from edge or center
17088
0
    if (outer_docking)
17089
0
    {
17090
        //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
17091
        //hs_h = ImFloor(hs_w * 0.15f);
17092
        //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
17093
0
        hs_w = ImFloor(hs_for_central_nodes * 1.50f);
17094
0
        hs_h = ImFloor(hs_for_central_nodes * 0.80f);
17095
0
        off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
17096
0
    }
17097
0
    else
17098
0
    {
17099
0
        hs_w = ImFloor(hs_for_central_nodes);
17100
0
        hs_h = ImFloor(hs_for_central_nodes * 0.90f);
17101
0
        off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
17102
0
    }
17103
17104
0
    ImVec2 c = ImFloor(parent.GetCenter());
17105
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
17106
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
17107
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
17108
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
17109
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
17110
17111
0
    if (test_mouse_pos == NULL)
17112
0
        return false;
17113
17114
0
    ImRect hit_r = out_r;
17115
0
    if (!outer_docking)
17116
0
    {
17117
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
17118
0
        hit_r.Expand(ImFloor(hs_w * 0.30f));
17119
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
17120
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
17121
0
        float r_threshold_center = hs_w * 1.4f;
17122
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
17123
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
17124
0
            return (dir == ImGuiDir_None);
17125
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
17126
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
17127
0
    }
17128
0
    return hit_r.Contains(*test_mouse_pos);
17129
0
}
17130
17131
// host_node may be NULL if the window doesn't have a DockNode already.
17132
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
17133
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
17134
0
{
17135
0
    ImGuiContext& g = *GImGui;
17136
17137
    // There is an edge case when docking into a dockspace which only has inactive nodes.
17138
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
17139
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
17140
0
    if (payload_node == NULL)
17141
0
        payload_node = payload_window->DockNodeAsHost;
17142
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
17143
0
    if (ref_node_for_rect)
17144
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
17145
17146
    // Filter, figure out where we are allowed to dock
17147
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
17148
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
17149
0
    data->IsCenterAvailable = true;
17150
0
    if (is_outer_docking)
17151
0
        data->IsCenterAvailable = false;
17152
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking)
17153
0
        data->IsCenterAvailable = false;
17154
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
17155
0
        data->IsCenterAvailable = false;
17156
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
17157
0
        data->IsCenterAvailable = false;
17158
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
17159
0
        data->IsCenterAvailable = false;
17160
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
17161
0
        data->IsCenterAvailable = false;
17162
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
17163
0
        data->IsCenterAvailable = false;
17164
17165
0
    data->IsSidesAvailable = true;
17166
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit)
17167
0
        data->IsSidesAvailable = false;
17168
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
17169
0
        data->IsSidesAvailable = false;
17170
0
    else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther))
17171
0
        data->IsSidesAvailable = false;
17172
17173
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
17174
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
17175
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
17176
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
17177
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
17178
17179
    // Calculate drop shapes geometry for allowed splitting directions
17180
0
    IM_ASSERT(ImGuiDir_None == -1);
17181
0
    data->SplitNode = host_node;
17182
0
    data->SplitDir = ImGuiDir_None;
17183
0
    data->IsSplitDirExplicit = false;
17184
0
    if (!host_window->Collapsed)
17185
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17186
0
        {
17187
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
17188
0
                continue;
17189
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
17190
0
                continue;
17191
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
17192
0
            {
17193
0
                data->SplitDir = (ImGuiDir)dir;
17194
0
                data->IsSplitDirExplicit = true;
17195
0
            }
17196
0
        }
17197
17198
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
17199
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
17200
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
17201
0
        data->IsDropAllowed = false;
17202
17203
    // Calculate split area
17204
0
    data->SplitRatio = 0.0f;
17205
0
    if (data->SplitDir != ImGuiDir_None)
17206
0
    {
17207
0
        ImGuiDir split_dir = data->SplitDir;
17208
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
17209
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
17210
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
17211
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
17212
17213
        // Calculate split ratio so we can pass it down the docking request
17214
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
17215
0
        data->FutureNode.Pos = pos_new;
17216
0
        data->FutureNode.Size = size_new;
17217
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
17218
0
    }
17219
0
}
17220
17221
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
17222
0
{
17223
0
    ImGuiContext& g = *GImGui;
17224
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
17225
17226
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
17227
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
17228
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
17229
17230
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
17231
0
    int overlay_draw_lists_count = 0;
17232
0
    ImDrawList* overlay_draw_lists[2];
17233
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
17234
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
17235
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
17236
17237
    // Draw main preview rectangle
17238
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
17239
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
17240
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
17241
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
17242
17243
    // Display area preview
17244
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
17245
0
    if (data->IsDropAllowed)
17246
0
    {
17247
0
        ImRect overlay_rect = data->FutureNode.Rect();
17248
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
17249
0
            overlay_rect.Min.y += GetFrameHeight();
17250
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
17251
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17252
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE));
17253
0
    }
17254
17255
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
17256
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
17257
0
    {
17258
        // Compute target tab bar geometry so we can locate our preview tabs
17259
0
        ImRect tab_bar_rect;
17260
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
17261
0
        ImVec2 tab_pos = tab_bar_rect.Min;
17262
0
        if (host_node && host_node->TabBar)
17263
0
        {
17264
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
17265
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
17266
0
            else
17267
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
17268
0
        }
17269
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
17270
0
        {
17271
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
17272
0
        }
17273
17274
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
17275
0
        if (root_payload->DockNodeAsHost)
17276
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
17277
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
17278
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
17279
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
17280
0
        {
17281
            // DockNode's TabBar may have non-window Tabs manually appended by user
17282
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
17283
0
            if (tab_bar_with_payload && payload_window == NULL)
17284
0
                continue;
17285
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
17286
0
                continue;
17287
17288
            // Calculate the tab bounding box for each payload window
17289
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
17290
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
17291
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
17292
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
17293
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
17294
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
17295
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17296
0
            {
17297
0
                ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
17298
0
                if (!tab_bar_rect.Contains(tab_bb))
17299
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
17300
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
17301
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
17302
0
                if (!tab_bar_rect.Contains(tab_bb))
17303
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
17304
0
            }
17305
0
            PopStyleColor();
17306
0
        }
17307
0
    }
17308
17309
    // Display drop boxes
17310
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
17311
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
17312
0
    {
17313
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
17314
0
        {
17315
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
17316
0
            ImRect draw_r_in = draw_r;
17317
0
            draw_r_in.Expand(-2.0f);
17318
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
17319
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
17320
0
            {
17321
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
17322
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
17323
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
17324
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
17325
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
17326
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
17327
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
17328
0
            }
17329
0
        }
17330
17331
        // Stop after ImGuiDir_None
17332
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
17333
0
            return;
17334
0
    }
17335
0
}
17336
17337
//-----------------------------------------------------------------------------
17338
// Docking: ImGuiDockNode Tree manipulation functions
17339
//-----------------------------------------------------------------------------
17340
// - DockNodeTreeSplit()
17341
// - DockNodeTreeMerge()
17342
// - DockNodeTreeUpdatePosSize()
17343
// - DockNodeTreeUpdateSplitterFindTouchingNode()
17344
// - DockNodeTreeUpdateSplitter()
17345
// - DockNodeTreeFindFallbackLeafNode()
17346
// - DockNodeTreeFindNodeByPos()
17347
//-----------------------------------------------------------------------------
17348
17349
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
17350
0
{
17351
0
    ImGuiContext& g = *GImGui;
17352
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
17353
17354
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
17355
0
    child_0->ParentNode = parent_node;
17356
17357
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
17358
0
    child_1->ParentNode = parent_node;
17359
17360
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
17361
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
17362
0
    parent_node->ChildNodes[0] = child_0;
17363
0
    parent_node->ChildNodes[1] = child_1;
17364
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
17365
0
    parent_node->SplitAxis = split_axis;
17366
0
    parent_node->VisibleWindow = NULL;
17367
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17368
17369
0
    float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE);
17370
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
17371
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
17372
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
17373
0
    child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
17374
0
    child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
17375
17376
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
17377
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
17378
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
17379
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
17380
17381
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
17382
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17383
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
17384
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17385
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17386
0
    child_0->UpdateMergedFlags();
17387
0
    child_1->UpdateMergedFlags();
17388
0
    parent_node->UpdateMergedFlags();
17389
0
    if (child_inheritor->IsCentralNode())
17390
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
17391
0
}
17392
17393
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
17394
0
{
17395
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
17396
0
    ImGuiContext& g = *GImGui;
17397
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
17398
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
17399
0
    IM_ASSERT(child_0 || child_1);
17400
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
17401
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
17402
0
    {
17403
0
        IM_ASSERT(parent_node->TabBar == NULL);
17404
0
        IM_ASSERT(parent_node->Windows.Size == 0);
17405
0
    }
17406
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
17407
17408
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
17409
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
17410
0
    if (child_0)
17411
0
    {
17412
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
17413
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
17414
0
    }
17415
0
    if (child_1)
17416
0
    {
17417
0
        DockNodeMoveWindows(parent_node, child_1);
17418
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
17419
0
    }
17420
0
    DockNodeApplyPosSizeToWindows(parent_node);
17421
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
17422
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
17423
0
    parent_node->SizeRef = backup_last_explicit_size;
17424
17425
    // Flags transfer
17426
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
17427
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17428
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
17429
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
17430
0
    parent_node->UpdateMergedFlags();
17431
17432
0
    if (child_0)
17433
0
    {
17434
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
17435
0
        IM_DELETE(child_0);
17436
0
    }
17437
0
    if (child_1)
17438
0
    {
17439
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
17440
0
        IM_DELETE(child_1);
17441
0
    }
17442
0
}
17443
17444
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
17445
// (Depth-first, Pre-Order)
17446
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
17447
0
{
17448
    // During the regular dock node update we write to all nodes.
17449
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
17450
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
17451
0
    if (write_to_node)
17452
0
    {
17453
0
        node->Pos = pos;
17454
0
        node->Size = size;
17455
0
    }
17456
17457
0
    if (node->IsLeafNode())
17458
0
        return;
17459
17460
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17461
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17462
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
17463
0
    ImVec2 child_0_size = size, child_1_size = size;
17464
17465
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
17466
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
17467
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
17468
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
17469
17470
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
17471
0
    {
17472
0
        ImGuiContext& g = *GImGui;
17473
0
        const float spacing = DOCKING_SPLITTER_SIZE;
17474
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17475
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
17476
17477
        // Size allocation policy
17478
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
17479
0
        const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
17480
17481
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
17482
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImFloor()
17483
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
17484
17485
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
17486
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
17487
0
        {
17488
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
17489
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17490
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17491
0
        }
17492
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
17493
0
        {
17494
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
17495
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
17496
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17497
0
        }
17498
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
17499
0
        {
17500
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
17501
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
17502
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
17503
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * split_ratio);
17504
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17505
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17506
0
        }
17507
17508
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
17509
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
17510
0
        {
17511
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
17512
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17513
0
        }
17514
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
17515
0
        {
17516
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
17517
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
17518
0
        }
17519
0
        else
17520
0
        {
17521
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17522
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17523
0
            child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5f));
17524
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17525
0
        }
17526
17527
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17528
0
    }
17529
17530
0
    if (only_write_to_single_node == NULL)
17531
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17532
17533
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17534
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17535
0
    if (child_0_recurse)
17536
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17537
0
    if (child_1_recurse)
17538
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17539
0
}
17540
17541
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17542
0
{
17543
0
    if (node->IsLeafNode())
17544
0
    {
17545
0
        touching_nodes->push_back(node);
17546
0
        return;
17547
0
    }
17548
0
    if (node->ChildNodes[0]->IsVisible)
17549
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17550
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17551
0
    if (node->ChildNodes[1]->IsVisible)
17552
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17553
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17554
0
}
17555
17556
// (Depth-First, Pre-Order)
17557
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17558
0
{
17559
0
    if (node->IsLeafNode())
17560
0
        return;
17561
17562
0
    ImGuiContext& g = *GImGui;
17563
17564
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17565
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17566
0
    if (child_0->IsVisible && child_1->IsVisible)
17567
0
    {
17568
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17569
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17570
0
        IM_ASSERT(axis != ImGuiAxis_None);
17571
0
        ImRect bb;
17572
0
        bb.Min = child_0->Pos;
17573
0
        bb.Max = child_1->Pos;
17574
0
        bb.Min[axis] += child_0->Size[axis];
17575
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17576
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17577
17578
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17579
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17580
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17581
0
        {
17582
0
            ImGuiWindow* window = g.CurrentWindow;
17583
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17584
0
        }
17585
0
        else
17586
0
        {
17587
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17588
            //bb.Max[axis] -= 1;
17589
0
            PushID(node->ID);
17590
17591
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17592
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17593
0
            float min_size = g.Style.WindowMinSize[axis];
17594
0
            float resize_limits[2];
17595
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17596
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17597
17598
0
            ImGuiID splitter_id = GetID("##Splitter");
17599
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17600
0
            {
17601
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17602
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17603
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17604
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17605
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17606
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17607
17608
                // [DEBUG] Render touching nodes & limits
17609
                /*
17610
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17611
                for (int n = 0; n < 2; n++)
17612
                {
17613
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17614
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17615
                    if (axis == ImGuiAxis_X)
17616
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17617
                    else
17618
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17619
                }
17620
                */
17621
0
            }
17622
17623
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17624
0
            float cur_size_0 = child_0->Size[axis];
17625
0
            float cur_size_1 = child_1->Size[axis];
17626
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17627
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17628
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17629
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17630
0
            {
17631
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17632
0
                {
17633
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17634
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17635
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17636
17637
                    // Lock the size of every node that is a sibling of the node we are touching
17638
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17639
0
                    for (int side_n = 0; side_n < 2; side_n++)
17640
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17641
0
                        {
17642
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17643
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17644
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17645
0
                            while (touching_node->ParentNode != node)
17646
0
                            {
17647
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17648
0
                                {
17649
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17650
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17651
0
                                    node_to_preserve->WantLockSizeOnce = true;
17652
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17653
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17654
0
                                }
17655
0
                                touching_node = touching_node->ParentNode;
17656
0
                            }
17657
0
                        }
17658
17659
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17660
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17661
0
                    MarkIniSettingsDirty();
17662
0
                }
17663
0
            }
17664
0
            PopID();
17665
0
        }
17666
0
    }
17667
17668
0
    if (child_0->IsVisible)
17669
0
        DockNodeTreeUpdateSplitter(child_0);
17670
0
    if (child_1->IsVisible)
17671
0
        DockNodeTreeUpdateSplitter(child_1);
17672
0
}
17673
17674
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17675
0
{
17676
0
    if (node->IsLeafNode())
17677
0
        return node;
17678
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17679
0
        return leaf_node;
17680
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17681
0
        return leaf_node;
17682
0
    return NULL;
17683
0
}
17684
17685
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17686
0
{
17687
0
    if (!node->IsVisible)
17688
0
        return NULL;
17689
17690
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17691
0
    ImRect r(node->Pos, node->Pos + node->Size);
17692
0
    r.Expand(dock_spacing * 0.5f);
17693
0
    bool inside = r.Contains(pos);
17694
0
    if (!inside)
17695
0
        return NULL;
17696
17697
0
    if (node->IsLeafNode())
17698
0
        return node;
17699
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17700
0
        return hovered_node;
17701
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17702
0
        return hovered_node;
17703
17704
    // This means we are hovering over the splitter/spacing of a parent node
17705
0
    return node;
17706
0
}
17707
17708
//-----------------------------------------------------------------------------
17709
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17710
//-----------------------------------------------------------------------------
17711
// - SetWindowDock() [Internal]
17712
// - DockSpace()
17713
// - DockSpaceOverViewport()
17714
//-----------------------------------------------------------------------------
17715
17716
// [Internal] Called via SetNextWindowDockID()
17717
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17718
0
{
17719
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17720
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17721
0
        return;
17722
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17723
17724
0
    if (window->DockId == dock_id)
17725
0
        return;
17726
17727
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17728
0
    ImGuiContext* ctx = GImGui;
17729
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17730
0
        if (new_node->IsSplitNode())
17731
0
        {
17732
            // Policy: Find central node or latest focused node. We first move back to our root node.
17733
0
            new_node = DockNodeGetRootNode(new_node);
17734
0
            if (new_node->CentralNode)
17735
0
            {
17736
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17737
0
                dock_id = new_node->CentralNode->ID;
17738
0
            }
17739
0
            else
17740
0
            {
17741
0
                dock_id = new_node->LastFocusedNodeId;
17742
0
            }
17743
0
        }
17744
17745
0
    if (window->DockId == dock_id)
17746
0
        return;
17747
17748
0
    if (window->DockNode)
17749
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
17750
0
    window->DockId = dock_id;
17751
0
}
17752
17753
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17754
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17755
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17756
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
17757
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17758
0
{
17759
0
    ImGuiContext* ctx = GImGui;
17760
0
    ImGuiContext& g = *ctx;
17761
0
    ImGuiWindow* window = GetCurrentWindowRead();
17762
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17763
0
        return 0;
17764
17765
    // Early out if parent window is hidden/collapsed
17766
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
17767
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
17768
0
    if (window->SkipItems)
17769
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
17770
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
17771
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
17772
17773
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
17774
0
    IM_ASSERT(id != 0);
17775
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
17776
0
    if (!node)
17777
0
    {
17778
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
17779
0
        node = DockContextAddNode(ctx, id);
17780
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
17781
0
    }
17782
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
17783
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
17784
0
    node->SharedFlags = flags;
17785
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
17786
17787
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
17788
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
17789
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
17790
0
    {
17791
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
17792
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17793
0
        return id;
17794
0
    }
17795
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17796
17797
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
17798
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
17799
0
    {
17800
0
        node->LastFrameAlive = g.FrameCount;
17801
0
        return id;
17802
0
    }
17803
17804
0
    const ImVec2 content_avail = GetContentRegionAvail();
17805
0
    ImVec2 size = ImFloor(size_arg);
17806
0
    if (size.x <= 0.0f)
17807
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
17808
0
    if (size.y <= 0.0f)
17809
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
17810
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17811
17812
0
    node->Pos = window->DC.CursorPos;
17813
0
    node->Size = node->SizeRef = size;
17814
0
    SetNextWindowPos(node->Pos);
17815
0
    SetNextWindowSize(node->Size);
17816
0
    g.NextWindowData.PosUndock = false;
17817
17818
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
17819
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
17820
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
17821
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
17822
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
17823
0
    window_flags |= ImGuiWindowFlags_NoBackground;
17824
17825
0
    char title[256];
17826
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
17827
17828
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
17829
0
    Begin(title, NULL, window_flags);
17830
0
    PopStyleVar();
17831
17832
0
    ImGuiWindow* host_window = g.CurrentWindow;
17833
0
    DockNodeSetupHostWindow(node, host_window);
17834
0
    host_window->ChildId = window->GetID(title);
17835
0
    node->OnlyNodeWithWindows = NULL;
17836
17837
0
    IM_ASSERT(node->IsRootNode());
17838
17839
    // We need to handle the rare case were a central node is missing.
17840
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
17841
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
17842
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
17843
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
17844
    // as it doesn't make sense for an empty dockspace to not have this property.
17845
0
    if (node->IsLeafNode() && !node->IsCentralNode())
17846
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17847
17848
    // Update the node
17849
0
    DockNodeUpdate(node);
17850
17851
0
    End();
17852
17853
0
    ImRect bb(node->Pos, node->Pos + size);
17854
0
    ItemSize(size);
17855
0
    ItemAdd(bb, id, NULL, ImGuiItemFlags_NoNav); // Not a nav point (could be, would need to draw the nav rect and replicate/refactor activation from BeginChild(), but seems like CTRL+Tab works better here?)
17856
0
    if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) && IsWindowChildOf(g.HoveredWindow, host_window, false, true)) // To fullfill IsItemHovered(), similar to EndChild()
17857
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
17858
17859
0
    return id;
17860
0
}
17861
17862
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
17863
// The limitation with this call is that your window won't have a menu bar.
17864
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
17865
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
17866
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
17867
0
{
17868
0
    if (viewport == NULL)
17869
0
        viewport = GetMainViewport();
17870
17871
0
    SetNextWindowPos(viewport->WorkPos);
17872
0
    SetNextWindowSize(viewport->WorkSize);
17873
0
    SetNextWindowViewport(viewport->ID);
17874
17875
0
    ImGuiWindowFlags host_window_flags = 0;
17876
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
17877
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
17878
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
17879
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
17880
17881
0
    char label[32];
17882
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
17883
17884
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
17885
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
17886
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
17887
0
    Begin(label, NULL, host_window_flags);
17888
0
    PopStyleVar(3);
17889
17890
0
    ImGuiID dockspace_id = GetID("DockSpace");
17891
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
17892
0
    End();
17893
17894
0
    return dockspace_id;
17895
0
}
17896
17897
//-----------------------------------------------------------------------------
17898
// Docking: Builder Functions
17899
//-----------------------------------------------------------------------------
17900
// Very early end-user API to manipulate dock nodes.
17901
// Only available in imgui_internal.h. Expect this API to change/break!
17902
// It is expected that those functions are all called _before_ the dockspace node submission.
17903
//-----------------------------------------------------------------------------
17904
// - DockBuilderDockWindow()
17905
// - DockBuilderGetNode()
17906
// - DockBuilderSetNodePos()
17907
// - DockBuilderSetNodeSize()
17908
// - DockBuilderAddNode()
17909
// - DockBuilderRemoveNode()
17910
// - DockBuilderRemoveNodeChildNodes()
17911
// - DockBuilderRemoveNodeDockedWindows()
17912
// - DockBuilderSplitNode()
17913
// - DockBuilderCopyNodeRec()
17914
// - DockBuilderCopyNode()
17915
// - DockBuilderCopyWindowSettings()
17916
// - DockBuilderCopyDockSpace()
17917
// - DockBuilderFinish()
17918
//-----------------------------------------------------------------------------
17919
17920
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
17921
0
{
17922
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
17923
0
    ImGuiContext& g = *GImGui; IM_UNUSED(g);
17924
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderDockWindow '%s' to node 0x%08X\n", window_name, node_id);
17925
0
    ImGuiID window_id = ImHashStr(window_name);
17926
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
17927
0
    {
17928
        // Apply to created window
17929
0
        ImGuiID prev_node_id = window->DockId;
17930
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
17931
0
        if (window->DockId != prev_node_id)
17932
0
            window->DockOrder = -1;
17933
0
    }
17934
0
    else
17935
0
    {
17936
        // Apply to settings
17937
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
17938
0
        if (settings == NULL)
17939
0
            settings = CreateNewWindowSettings(window_name);
17940
0
        if (settings->DockId != node_id)
17941
0
            settings->DockOrder = -1;
17942
0
        settings->DockId = node_id;
17943
0
    }
17944
0
}
17945
17946
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
17947
0
{
17948
0
    ImGuiContext* ctx = GImGui;
17949
0
    return DockContextFindNodeByID(ctx, node_id);
17950
0
}
17951
17952
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
17953
0
{
17954
0
    ImGuiContext* ctx = GImGui;
17955
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17956
0
    if (node == NULL)
17957
0
        return;
17958
0
    node->Pos = pos;
17959
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
17960
0
}
17961
17962
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
17963
0
{
17964
0
    ImGuiContext* ctx = GImGui;
17965
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17966
0
    if (node == NULL)
17967
0
        return;
17968
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17969
0
    node->Size = node->SizeRef = size;
17970
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17971
0
}
17972
17973
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
17974
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
17975
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
17976
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
17977
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
17978
// - Use (id == 0) to let the system allocate a node identifier.
17979
// - Existing node with a same id will be removed.
17980
ImGuiID ImGui::DockBuilderAddNode(ImGuiID node_id, ImGuiDockNodeFlags flags)
17981
0
{
17982
0
    ImGuiContext* ctx = GImGui;
17983
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
17984
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderAddNode 0x%08X flags=%08X\n", node_id, flags);
17985
17986
0
    if (node_id != 0)
17987
0
        DockBuilderRemoveNode(node_id);
17988
17989
0
    ImGuiDockNode* node = NULL;
17990
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
17991
0
    {
17992
0
        DockSpace(node_id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
17993
0
        node = DockContextFindNodeByID(ctx, node_id);
17994
0
    }
17995
0
    else
17996
0
    {
17997
0
        node = DockContextAddNode(ctx, node_id);
17998
0
        node->SetLocalFlags(flags);
17999
0
    }
18000
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
18001
0
    return node->ID;
18002
0
}
18003
18004
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
18005
0
{
18006
0
    ImGuiContext* ctx = GImGui;
18007
0
    ImGuiContext& g = *ctx; IM_UNUSED(g);
18008
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderRemoveNode 0x%08X\n", node_id);
18009
18010
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
18011
0
    if (node == NULL)
18012
0
        return;
18013
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
18014
0
    DockBuilderRemoveNodeChildNodes(node_id);
18015
    // Node may have moved or deleted if e.g. any merge happened
18016
0
    node = DockContextFindNodeByID(ctx, node_id);
18017
0
    if (node == NULL)
18018
0
        return;
18019
0
    if (node->IsCentralNode() && node->ParentNode)
18020
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18021
0
    DockContextRemoveNode(ctx, node, true);
18022
0
}
18023
18024
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
18025
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
18026
0
{
18027
0
    ImGuiContext* ctx = GImGui;
18028
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18029
18030
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
18031
0
    if (root_id && root_node == NULL)
18032
0
        return;
18033
0
    bool has_central_node = false;
18034
18035
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
18036
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
18037
18038
    // Process active windows
18039
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
18040
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18041
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18042
0
        {
18043
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
18044
0
            if (want_removal)
18045
0
            {
18046
0
                if (node->IsCentralNode())
18047
0
                    has_central_node = true;
18048
0
                if (root_id != 0)
18049
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
18050
0
                if (root_node)
18051
0
                {
18052
0
                    DockNodeMoveWindows(root_node, node);
18053
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
18054
0
                }
18055
0
                nodes_to_remove.push_back(node);
18056
0
            }
18057
0
        }
18058
18059
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
18060
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
18061
0
    if (root_node)
18062
0
    {
18063
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
18064
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
18065
0
    }
18066
18067
    // Apply to settings
18068
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
18069
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
18070
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
18071
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
18072
0
                {
18073
0
                    settings->DockId = root_id;
18074
0
                    break;
18075
0
                }
18076
18077
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
18078
0
    if (nodes_to_remove.Size > 1)
18079
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
18080
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
18081
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
18082
18083
0
    if (root_id == 0)
18084
0
    {
18085
0
        dc->Nodes.Clear();
18086
0
        dc->Requests.clear();
18087
0
    }
18088
0
    else if (has_central_node)
18089
0
    {
18090
0
        root_node->CentralNode = root_node;
18091
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
18092
0
    }
18093
0
}
18094
18095
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
18096
0
{
18097
    // Clear references in settings
18098
0
    ImGuiContext* ctx = GImGui;
18099
0
    ImGuiContext& g = *ctx;
18100
0
    if (clear_settings_refs)
18101
0
    {
18102
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18103
0
        {
18104
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
18105
0
            if (!want_removal && settings->DockId != 0)
18106
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
18107
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
18108
0
                        want_removal = true;
18109
0
            if (want_removal)
18110
0
                settings->DockId = 0;
18111
0
        }
18112
0
    }
18113
18114
    // Clear references in windows
18115
0
    for (int n = 0; n < g.Windows.Size; n++)
18116
0
    {
18117
0
        ImGuiWindow* window = g.Windows[n];
18118
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
18119
0
        if (want_removal)
18120
0
        {
18121
0
            const ImGuiID backup_dock_id = window->DockId;
18122
0
            IM_UNUSED(backup_dock_id);
18123
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
18124
0
            if (!clear_settings_refs)
18125
0
                IM_ASSERT(window->DockId == backup_dock_id);
18126
0
        }
18127
0
    }
18128
0
}
18129
18130
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
18131
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
18132
// FIXME-DOCK: We are not exposing nor using split_outer.
18133
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
18134
0
{
18135
0
    ImGuiContext& g = *GImGui;
18136
0
    IM_ASSERT(split_dir != ImGuiDir_None);
18137
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
18138
18139
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
18140
0
    if (node == NULL)
18141
0
    {
18142
0
        IM_ASSERT(node != NULL);
18143
0
        return 0;
18144
0
    }
18145
18146
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
18147
18148
0
    ImGuiDockRequest req;
18149
0
    req.Type = ImGuiDockRequestType_Split;
18150
0
    req.DockTargetWindow = NULL;
18151
0
    req.DockTargetNode = node;
18152
0
    req.DockPayload = NULL;
18153
0
    req.DockSplitDir = split_dir;
18154
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
18155
0
    req.DockSplitOuter = false;
18156
0
    DockContextProcessDock(&g, &req);
18157
18158
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
18159
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
18160
0
    if (out_id_at_dir)
18161
0
        *out_id_at_dir = id_at_dir;
18162
0
    if (out_id_at_opposite_dir)
18163
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
18164
0
    return id_at_dir;
18165
0
}
18166
18167
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
18168
0
{
18169
0
    ImGuiContext& g = *GImGui;
18170
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
18171
0
    dst_node->SharedFlags = src_node->SharedFlags;
18172
0
    dst_node->LocalFlags = src_node->LocalFlags;
18173
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
18174
0
    dst_node->Pos = src_node->Pos;
18175
0
    dst_node->Size = src_node->Size;
18176
0
    dst_node->SizeRef = src_node->SizeRef;
18177
0
    dst_node->SplitAxis = src_node->SplitAxis;
18178
0
    dst_node->UpdateMergedFlags();
18179
18180
0
    out_node_remap_pairs->push_back(src_node->ID);
18181
0
    out_node_remap_pairs->push_back(dst_node->ID);
18182
18183
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
18184
0
        if (src_node->ChildNodes[child_n])
18185
0
        {
18186
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
18187
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
18188
0
        }
18189
18190
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
18191
0
    return dst_node;
18192
0
}
18193
18194
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
18195
0
{
18196
0
    ImGuiContext* ctx = GImGui;
18197
0
    IM_ASSERT(src_node_id != 0);
18198
0
    IM_ASSERT(dst_node_id != 0);
18199
0
    IM_ASSERT(out_node_remap_pairs != NULL);
18200
18201
0
    DockBuilderRemoveNode(dst_node_id);
18202
18203
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
18204
0
    IM_ASSERT(src_node != NULL);
18205
18206
0
    out_node_remap_pairs->clear();
18207
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
18208
18209
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
18210
0
}
18211
18212
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
18213
0
{
18214
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
18215
0
    if (src_window == NULL)
18216
0
        return;
18217
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
18218
0
    {
18219
0
        dst_window->Pos = src_window->Pos;
18220
0
        dst_window->Size = src_window->Size;
18221
0
        dst_window->SizeFull = src_window->SizeFull;
18222
0
        dst_window->Collapsed = src_window->Collapsed;
18223
0
    }
18224
0
    else
18225
0
    {
18226
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
18227
0
        if (!dst_settings)
18228
0
            dst_settings = CreateNewWindowSettings(dst_name);
18229
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
18230
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
18231
0
        {
18232
0
            dst_settings->ViewportPos = window_pos_2ih;
18233
0
            dst_settings->ViewportId = src_window->ViewportId;
18234
0
            dst_settings->Pos = ImVec2ih(0, 0);
18235
0
        }
18236
0
        else
18237
0
        {
18238
0
            dst_settings->Pos = window_pos_2ih;
18239
0
        }
18240
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
18241
0
        dst_settings->Collapsed = src_window->Collapsed;
18242
0
    }
18243
0
}
18244
18245
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
18246
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
18247
0
{
18248
0
    ImGuiContext& g = *GImGui;
18249
0
    IM_ASSERT(src_dockspace_id != 0);
18250
0
    IM_ASSERT(dst_dockspace_id != 0);
18251
0
    IM_ASSERT(in_window_remap_pairs != NULL);
18252
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
18253
18254
    // Duplicate entire dock
18255
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
18256
    // whereas we could attempt to at least keep them together in a new, same floating node.
18257
0
    ImVector<ImGuiID> node_remap_pairs;
18258
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
18259
18260
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
18261
    // (The windows associated to src_dockspace_id are staying in place)
18262
0
    ImVector<ImGuiID> src_windows;
18263
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
18264
0
    {
18265
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
18266
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
18267
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
18268
0
        src_windows.push_back(src_window_id);
18269
18270
        // Search in the remapping tables
18271
0
        ImGuiID src_dock_id = 0;
18272
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
18273
0
            src_dock_id = src_window->DockId;
18274
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
18275
0
            src_dock_id = src_window_settings->DockId;
18276
0
        ImGuiID dst_dock_id = 0;
18277
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18278
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
18279
0
            {
18280
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18281
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
18282
0
                break;
18283
0
            }
18284
18285
0
        if (dst_dock_id != 0)
18286
0
        {
18287
            // Docked windows gets redocked into the new node hierarchy.
18288
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
18289
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
18290
0
        }
18291
0
        else
18292
0
        {
18293
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
18294
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
18295
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
18296
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
18297
0
        }
18298
0
    }
18299
18300
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
18301
    // Find those windows and move to them to the cloned dock node. This may be optional?
18302
    // Dock those are a second step as undocking would invalidate source dock nodes.
18303
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
18304
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
18305
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
18306
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
18307
0
        {
18308
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
18309
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
18310
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
18311
0
            {
18312
0
                ImGuiWindow* window = node->Windows[window_n];
18313
0
                if (src_windows.contains(window->ID))
18314
0
                    continue;
18315
18316
                // Docked windows gets redocked into the new node hierarchy.
18317
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
18318
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
18319
0
            }
18320
0
        }
18321
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
18322
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
18323
0
}
18324
18325
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
18326
void ImGui::DockBuilderFinish(ImGuiID root_id)
18327
0
{
18328
0
    ImGuiContext* ctx = GImGui;
18329
    //DockContextRebuild(ctx);
18330
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
18331
0
}
18332
18333
//-----------------------------------------------------------------------------
18334
// Docking: Begin/End Support Functions (called from Begin/End)
18335
//-----------------------------------------------------------------------------
18336
// - GetWindowAlwaysWantOwnTabBar()
18337
// - DockContextBindNodeToWindow()
18338
// - BeginDocked()
18339
// - BeginDockableDragDropSource()
18340
// - BeginDockableDragDropTarget()
18341
//-----------------------------------------------------------------------------
18342
18343
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
18344
45.5k
{
18345
45.5k
    ImGuiContext& g = *GImGui;
18346
45.5k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
18347
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
18348
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
18349
0
                return true;
18350
45.5k
    return false;
18351
45.5k
}
18352
18353
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
18354
0
{
18355
0
    ImGuiContext& g = *ctx;
18356
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
18357
0
    IM_ASSERT(window->DockNode == NULL);
18358
18359
    // We should not be docking into a split node (SetWindowDock should avoid this)
18360
0
    if (node && node->IsSplitNode())
18361
0
    {
18362
0
        DockContextProcessUndockWindow(ctx, window);
18363
0
        return NULL;
18364
0
    }
18365
18366
    // Create node
18367
0
    if (node == NULL)
18368
0
    {
18369
0
        node = DockContextAddNode(ctx, window->DockId);
18370
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
18371
0
        node->LastFrameAlive = g.FrameCount;
18372
0
    }
18373
18374
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
18375
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
18376
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
18377
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
18378
0
    if (!node->IsVisible)
18379
0
    {
18380
0
        ImGuiDockNode* ancestor_node = node;
18381
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
18382
0
            ancestor_node = ancestor_node->ParentNode;
18383
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
18384
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
18385
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
18386
0
    }
18387
18388
    // Add window to node
18389
0
    bool node_was_visible = node->IsVisible;
18390
0
    DockNodeAddWindow(node, window, true);
18391
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
18392
0
    IM_ASSERT(node == window->DockNode);
18393
0
    return node;
18394
0
}
18395
18396
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
18397
0
{
18398
0
    ImGuiContext* ctx = GImGui;
18399
0
    ImGuiContext& g = *ctx;
18400
18401
    // Clear fields ahead so most early-out paths don't have to do it
18402
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
18403
18404
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
18405
0
    if (auto_dock_node)
18406
0
    {
18407
0
        if (window->DockId == 0)
18408
0
        {
18409
0
            IM_ASSERT(window->DockNode == NULL);
18410
0
            window->DockId = DockContextGenNodeID(ctx);
18411
0
        }
18412
0
    }
18413
0
    else
18414
0
    {
18415
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
18416
0
        bool want_undock = false;
18417
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
18418
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
18419
0
        if (want_undock)
18420
0
        {
18421
0
            DockContextProcessUndockWindow(ctx, window);
18422
0
            return;
18423
0
        }
18424
0
    }
18425
18426
    // Bind to our dock node
18427
0
    ImGuiDockNode* node = window->DockNode;
18428
0
    if (node != NULL)
18429
0
        IM_ASSERT(window->DockId == node->ID);
18430
0
    if (window->DockId != 0 && node == NULL)
18431
0
    {
18432
0
        node = DockContextBindNodeToWindow(ctx, window);
18433
0
        if (node == NULL)
18434
0
            return;
18435
0
    }
18436
18437
#if 0
18438
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
18439
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
18440
    {
18441
        DockContextProcessUndockWindow(ctx, window);
18442
        return;
18443
    }
18444
#endif
18445
18446
    // Undock if our dockspace node disappeared
18447
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
18448
0
    if (node->LastFrameAlive < g.FrameCount)
18449
0
    {
18450
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
18451
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
18452
0
        if (root_node->LastFrameAlive < g.FrameCount)
18453
0
            DockContextProcessUndockWindow(ctx, window);
18454
0
        else
18455
0
            window->DockIsActive = true;
18456
0
        return;
18457
0
    }
18458
18459
    // Store style overrides
18460
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18461
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18462
18463
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
18464
    // and never create neither a host window neither a tab bar.
18465
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
18466
0
    if (node->HostWindow == NULL)
18467
0
    {
18468
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
18469
0
            window->DockIsActive = true;
18470
0
        if (node->Windows.Size > 1 && window->Appearing) // Only hide appearing window
18471
0
            DockNodeHideWindowDuringHostWindowCreation(window);
18472
0
        return;
18473
0
    }
18474
18475
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
18476
0
    IM_ASSERT(node->HostWindow);
18477
0
    IM_ASSERT(node->IsLeafNode());
18478
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
18479
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
18480
18481
    // Undock if we are submitted earlier than the host window
18482
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
18483
0
    {
18484
0
        DockContextProcessUndockWindow(ctx, window);
18485
0
        return;
18486
0
    }
18487
18488
    // Position/Size window
18489
0
    SetNextWindowPos(node->Pos);
18490
0
    SetNextWindowSize(node->Size);
18491
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
18492
0
    window->DockIsActive = true;
18493
0
    window->DockNodeIsVisible = true;
18494
0
    window->DockTabIsVisible = false;
18495
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18496
0
        return;
18497
18498
    // When the window is selected we mark it as visible.
18499
0
    if (node->VisibleWindow == window)
18500
0
        window->DockTabIsVisible = true;
18501
18502
    // Update window flag
18503
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
18504
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
18505
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
18506
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
18507
0
    else
18508
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
18509
18510
    // Save new dock order only if the window has been visible once already
18511
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
18512
0
    if (node->TabBar && window->WasActive)
18513
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
18514
18515
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
18516
0
        *p_open = false;
18517
18518
    // Update ChildId to allow returning from Child to Parent with Escape
18519
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
18520
0
    window->ChildId = parent_window->GetID(window->Name);
18521
0
}
18522
18523
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
18524
28
{
18525
28
    ImGuiContext& g = *GImGui;
18526
28
    IM_ASSERT(g.ActiveId == window->MoveId);
18527
28
    IM_ASSERT(g.MovingWindow == window);
18528
28
    IM_ASSERT(g.CurrentWindow == window);
18529
18530
28
    g.LastItemData.ID = window->MoveId;
18531
28
    window = window->RootWindowDockTree;
18532
28
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18533
28
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
18534
28
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
18535
5
    {
18536
5
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
18537
5
        EndDragDropSource();
18538
18539
        // Store style overrides
18540
35
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18541
30
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18542
5
    }
18543
28
}
18544
18545
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18546
14
{
18547
14
    ImGuiContext* ctx = GImGui;
18548
14
    ImGuiContext& g = *ctx;
18549
18550
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18551
14
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18552
14
    if (!g.DragDropActive)
18553
0
        return;
18554
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18555
14
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18556
14
        return;
18557
18558
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18559
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18560
0
    const ImGuiPayload* payload = &g.DragDropPayload;
18561
0
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18562
0
    {
18563
0
        EndDragDropTarget();
18564
0
        return;
18565
0
    }
18566
18567
0
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18568
0
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18569
0
    {
18570
        // Select target node
18571
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18572
0
        bool dock_into_floating_window = false;
18573
0
        ImGuiDockNode* node = NULL;
18574
0
        if (window->DockNodeAsHost)
18575
0
        {
18576
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18577
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18578
18579
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18580
            // In this case we need to fallback into any leaf mode, possibly the central node.
18581
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18582
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18583
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18584
0
        }
18585
0
        else
18586
0
        {
18587
0
            if (window->DockNode)
18588
0
                node = window->DockNode;
18589
0
            else
18590
0
                dock_into_floating_window = true; // Dock into a regular window
18591
0
        }
18592
18593
0
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18594
0
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18595
18596
        // Preview docking request and find out split direction/ratio
18597
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18598
0
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18599
0
        if (do_preview && (node != NULL || dock_into_floating_window))
18600
0
        {
18601
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18602
0
            ImGuiDockPreviewData split_inner;
18603
0
            ImGuiDockPreviewData split_outer;
18604
0
            ImGuiDockPreviewData* split_data = &split_inner;
18605
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18606
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18607
0
                {
18608
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18609
0
                    if (split_outer.IsSplitDirExplicit)
18610
0
                        split_data = &split_outer;
18611
0
                }
18612
0
            if (!node || node->IsLeafNode())
18613
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18614
0
            if (split_data == &split_outer)
18615
0
                split_inner.IsDropAllowed = false;
18616
18617
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18618
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18619
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18620
18621
            // Queue docking request
18622
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18623
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18624
0
        }
18625
0
    }
18626
0
    EndDragDropTarget();
18627
0
}
18628
18629
//-----------------------------------------------------------------------------
18630
// Docking: Settings
18631
//-----------------------------------------------------------------------------
18632
// - DockSettingsRenameNodeReferences()
18633
// - DockSettingsRemoveNodeReferences()
18634
// - DockSettingsFindNodeSettings()
18635
// - DockSettingsHandler_ApplyAll()
18636
// - DockSettingsHandler_ReadOpen()
18637
// - DockSettingsHandler_ReadLine()
18638
// - DockSettingsHandler_DockNodeToSettings()
18639
// - DockSettingsHandler_WriteAll()
18640
//-----------------------------------------------------------------------------
18641
18642
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18643
0
{
18644
0
    ImGuiContext& g = *GImGui;
18645
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18646
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18647
0
    {
18648
0
        ImGuiWindow* window = g.Windows[window_n];
18649
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18650
0
            window->DockId = new_node_id;
18651
0
    }
18652
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18653
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18654
0
        if (settings->DockId == old_node_id)
18655
0
            settings->DockId = new_node_id;
18656
0
}
18657
18658
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18659
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18660
0
{
18661
0
    ImGuiContext& g = *GImGui;
18662
0
    int found = 0;
18663
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18664
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18665
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18666
0
            if (settings->DockId == node_ids[node_n])
18667
0
            {
18668
0
                settings->DockId = 0;
18669
0
                settings->DockOrder = -1;
18670
0
                if (++found < node_ids_count)
18671
0
                    break;
18672
0
                return;
18673
0
            }
18674
0
}
18675
18676
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18677
0
{
18678
    // FIXME-OPT
18679
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18680
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18681
0
        if (dc->NodesSettings[n].ID == id)
18682
0
            return &dc->NodesSettings[n];
18683
0
    return NULL;
18684
0
}
18685
18686
// Clear settings data
18687
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18688
0
{
18689
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18690
0
    dc->NodesSettings.clear();
18691
0
    DockContextClearNodes(ctx, 0, true);
18692
0
}
18693
18694
// Recreate nodes based on settings data
18695
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18696
0
{
18697
    // Prune settings at boot time only
18698
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18699
0
    if (ctx->Windows.Size == 0)
18700
0
        DockContextPruneUnusedSettingsNodes(ctx);
18701
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18702
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18703
0
}
18704
18705
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18706
0
{
18707
0
    if (strcmp(name, "Data") != 0)
18708
0
        return NULL;
18709
0
    return (void*)1;
18710
0
}
18711
18712
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18713
0
{
18714
0
    char c = 0;
18715
0
    int x = 0, y = 0;
18716
0
    int r = 0;
18717
18718
    // Parsing, e.g.
18719
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18720
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18721
    // Important: this code expect currently fields in a fixed order.
18722
0
    ImGuiDockNodeSettings node;
18723
0
    line = ImStrSkipBlank(line);
18724
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18725
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18726
0
    else return;
18727
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18728
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18729
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18730
0
    if (node.ParentNodeId == 0)
18731
0
    {
18732
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18733
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18734
0
    }
18735
0
    else
18736
0
    {
18737
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18738
0
    }
18739
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18740
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18741
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18742
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18743
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18744
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18745
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18746
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18747
0
    if (node.ParentNodeId != 0)
18748
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18749
0
            node.Depth = parent_settings->Depth + 1;
18750
0
    ctx->DockContext.NodesSettings.push_back(node);
18751
0
}
18752
18753
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
18754
0
{
18755
0
    ImGuiDockNodeSettings node_settings;
18756
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
18757
0
    node_settings.ID = node->ID;
18758
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
18759
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
18760
0
    node_settings.SelectedTabId = node->SelectedTabId;
18761
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
18762
0
    node_settings.Depth = (char)depth;
18763
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
18764
0
    node_settings.Pos = ImVec2ih(node->Pos);
18765
0
    node_settings.Size = ImVec2ih(node->Size);
18766
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
18767
0
    dc->NodesSettings.push_back(node_settings);
18768
0
    if (node->ChildNodes[0])
18769
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
18770
0
    if (node->ChildNodes[1])
18771
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
18772
0
}
18773
18774
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
18775
0
{
18776
0
    ImGuiContext& g = *ctx;
18777
0
    ImGuiDockContext* dc = &ctx->DockContext;
18778
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18779
0
        return;
18780
18781
    // Gather settings data
18782
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
18783
0
    dc->NodesSettings.resize(0);
18784
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
18785
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18786
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18787
0
            if (node->IsRootNode())
18788
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
18789
18790
0
    int max_depth = 0;
18791
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18792
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
18793
18794
    // Write to text buffer
18795
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
18796
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18797
0
    {
18798
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
18799
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
18800
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
18801
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
18802
0
        if (node_settings->ParentNodeId)
18803
0
        {
18804
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
18805
0
        }
18806
0
        else
18807
0
        {
18808
0
            if (node_settings->ParentWindowId)
18809
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
18810
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
18811
0
        }
18812
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
18813
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
18814
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
18815
0
            buf->appendf(" NoResize=1");
18816
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
18817
0
            buf->appendf(" CentralNode=1");
18818
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
18819
0
            buf->appendf(" NoTabBar=1");
18820
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
18821
0
            buf->appendf(" HiddenTabBar=1");
18822
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
18823
0
            buf->appendf(" NoWindowMenuButton=1");
18824
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
18825
0
            buf->appendf(" NoCloseButton=1");
18826
0
        if (node_settings->SelectedTabId)
18827
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
18828
18829
        // [DEBUG] Include comments in the .ini file to ease debugging (this makes saving slower!)
18830
0
        if (g.IO.ConfigDebugIniSettings)
18831
0
            if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
18832
0
            {
18833
0
                buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
18834
0
                if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
18835
0
                    buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
18836
                // Iterate settings so we can give info about windows that didn't exist during the session.
18837
0
                int contains_window = 0;
18838
0
                for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18839
0
                    if (settings->DockId == node_settings->ID)
18840
0
                    {
18841
0
                        if (contains_window++ == 0)
18842
0
                            buf->appendf(" ; contains ");
18843
0
                        buf->appendf("'%s' ", settings->GetName());
18844
0
                    }
18845
0
            }
18846
18847
0
        buf->appendf("\n");
18848
0
    }
18849
0
    buf->appendf("\n");
18850
0
}
18851
18852
18853
//-----------------------------------------------------------------------------
18854
// [SECTION] PLATFORM DEPENDENT HELPERS
18855
//-----------------------------------------------------------------------------
18856
18857
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
18858
18859
#ifdef _MSC_VER
18860
#pragma comment(lib, "user32")
18861
#pragma comment(lib, "kernel32")
18862
#endif
18863
18864
// Win32 clipboard implementation
18865
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
18866
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18867
{
18868
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18869
    g.ClipboardHandlerData.clear();
18870
    if (!::OpenClipboard(NULL))
18871
        return NULL;
18872
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
18873
    if (wbuf_handle == NULL)
18874
    {
18875
        ::CloseClipboard();
18876
        return NULL;
18877
    }
18878
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
18879
    {
18880
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
18881
        g.ClipboardHandlerData.resize(buf_len);
18882
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
18883
    }
18884
    ::GlobalUnlock(wbuf_handle);
18885
    ::CloseClipboard();
18886
    return g.ClipboardHandlerData.Data;
18887
}
18888
18889
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18890
{
18891
    if (!::OpenClipboard(NULL))
18892
        return;
18893
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
18894
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
18895
    if (wbuf_handle == NULL)
18896
    {
18897
        ::CloseClipboard();
18898
        return;
18899
    }
18900
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
18901
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
18902
    ::GlobalUnlock(wbuf_handle);
18903
    ::EmptyClipboard();
18904
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
18905
        ::GlobalFree(wbuf_handle);
18906
    ::CloseClipboard();
18907
}
18908
18909
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
18910
18911
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
18912
static PasteboardRef main_clipboard = 0;
18913
18914
// OSX clipboard implementation
18915
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
18916
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18917
{
18918
    if (!main_clipboard)
18919
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18920
    PasteboardClear(main_clipboard);
18921
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
18922
    if (cf_data)
18923
    {
18924
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
18925
        CFRelease(cf_data);
18926
    }
18927
}
18928
18929
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18930
{
18931
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18932
    if (!main_clipboard)
18933
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18934
    PasteboardSynchronize(main_clipboard);
18935
18936
    ItemCount item_count = 0;
18937
    PasteboardGetItemCount(main_clipboard, &item_count);
18938
    for (ItemCount i = 0; i < item_count; i++)
18939
    {
18940
        PasteboardItemID item_id = 0;
18941
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
18942
        CFArrayRef flavor_type_array = 0;
18943
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
18944
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
18945
        {
18946
            CFDataRef cf_data;
18947
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
18948
            {
18949
                g.ClipboardHandlerData.clear();
18950
                int length = (int)CFDataGetLength(cf_data);
18951
                g.ClipboardHandlerData.resize(length + 1);
18952
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
18953
                g.ClipboardHandlerData[length] = 0;
18954
                CFRelease(cf_data);
18955
                return g.ClipboardHandlerData.Data;
18956
            }
18957
        }
18958
    }
18959
    return NULL;
18960
}
18961
18962
#else
18963
18964
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
18965
static const char* GetClipboardTextFn_DefaultImpl(void* user_data_ctx)
18966
0
{
18967
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18968
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
18969
0
}
18970
18971
static void SetClipboardTextFn_DefaultImpl(void* user_data_ctx, const char* text)
18972
0
{
18973
0
    ImGuiContext& g = *(ImGuiContext*)user_data_ctx;
18974
0
    g.ClipboardHandlerData.clear();
18975
0
    const char* text_end = text + strlen(text);
18976
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
18977
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
18978
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
18979
0
}
18980
18981
#endif
18982
18983
// Win32 API IME support (for Asian languages, etc.)
18984
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
18985
18986
#include <imm.h>
18987
#ifdef _MSC_VER
18988
#pragma comment(lib, "imm32")
18989
#endif
18990
18991
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
18992
{
18993
    // Notify OS Input Method Editor of text input position
18994
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
18995
    if (hwnd == 0)
18996
        return;
18997
18998
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
18999
    if (HIMC himc = ::ImmGetContext(hwnd))
19000
    {
19001
        COMPOSITIONFORM composition_form = {};
19002
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19003
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19004
        composition_form.dwStyle = CFS_FORCE_POSITION;
19005
        ::ImmSetCompositionWindow(himc, &composition_form);
19006
        CANDIDATEFORM candidate_form = {};
19007
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
19008
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
19009
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
19010
        ::ImmSetCandidateWindow(himc, &candidate_form);
19011
        ::ImmReleaseContext(hwnd, himc);
19012
    }
19013
}
19014
19015
#else
19016
19017
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
19018
19019
#endif
19020
19021
//-----------------------------------------------------------------------------
19022
// [SECTION] METRICS/DEBUGGER WINDOW
19023
//-----------------------------------------------------------------------------
19024
// - RenderViewportThumbnail() [Internal]
19025
// - RenderViewportsThumbnails() [Internal]
19026
// - DebugTextEncoding()
19027
// - MetricsHelpMarker() [Internal]
19028
// - ShowFontAtlas() [Internal]
19029
// - ShowMetricsWindow()
19030
// - DebugNodeColumns() [Internal]
19031
// - DebugNodeDockNode() [Internal]
19032
// - DebugNodeDrawList() [Internal]
19033
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
19034
// - DebugNodeFont() [Internal]
19035
// - DebugNodeFontGlyph() [Internal]
19036
// - DebugNodeStorage() [Internal]
19037
// - DebugNodeTabBar() [Internal]
19038
// - DebugNodeViewport() [Internal]
19039
// - DebugNodeWindow() [Internal]
19040
// - DebugNodeWindowSettings() [Internal]
19041
// - DebugNodeWindowsList() [Internal]
19042
// - DebugNodeWindowsListByBeginStackParent() [Internal]
19043
//-----------------------------------------------------------------------------
19044
19045
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
19046
19047
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
19048
0
{
19049
0
    ImGuiContext& g = *GImGui;
19050
0
    ImGuiWindow* window = g.CurrentWindow;
19051
19052
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
19053
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
19054
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_IsMinimized) ? 0.30f : 1.00f;
19055
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
19056
0
    for (int i = 0; i != g.Windows.Size; i++)
19057
0
    {
19058
0
        ImGuiWindow* thumb_window = g.Windows[i];
19059
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
19060
0
            continue;
19061
0
        if (thumb_window->Viewport != viewport)
19062
0
            continue;
19063
19064
0
        ImRect thumb_r = thumb_window->Rect();
19065
0
        ImRect title_r = thumb_window->TitleBarRect();
19066
0
        thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));
19067
0
        title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
19068
0
        thumb_r.ClipWithFull(bb);
19069
0
        title_r.ClipWithFull(bb);
19070
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
19071
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
19072
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
19073
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19074
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
19075
0
    }
19076
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
19077
0
}
19078
19079
static void RenderViewportsThumbnails()
19080
0
{
19081
0
    ImGuiContext& g = *GImGui;
19082
0
    ImGuiWindow* window = g.CurrentWindow;
19083
19084
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
19085
0
    float SCALE = 1.0f / 8.0f;
19086
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19087
0
    for (int n = 0; n < g.Viewports.Size; n++)
19088
0
        bb_full.Add(g.Viewports[n]->GetMainRect());
19089
0
    ImVec2 p = window->DC.CursorPos;
19090
0
    ImVec2 off = p - bb_full.Min * SCALE;
19091
0
    for (int n = 0; n < g.Viewports.Size; n++)
19092
0
    {
19093
0
        ImGuiViewportP* viewport = g.Viewports[n];
19094
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
19095
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
19096
0
    }
19097
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
19098
0
}
19099
19100
static int IMGUI_CDECL ViewportComparerByLastFocusedStampCount(const void* lhs, const void* rhs)
19101
0
{
19102
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
19103
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
19104
0
    return b->LastFocusedStampCount - a->LastFocusedStampCount;
19105
0
}
19106
19107
// Draw an arbitrary US keyboard layout to visualize translated keys
19108
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
19109
0
{
19110
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
19111
0
    const float  key_rounding = 3.0f;
19112
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
19113
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
19114
0
    const float  key_face_rounding = 2.0f;
19115
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
19116
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
19117
0
    const float  key_row_offset = 9.0f;
19118
19119
0
    ImVec2 board_min = GetCursorScreenPos();
19120
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
19121
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
19122
19123
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
19124
0
    const KeyLayoutData keys_to_display[] =
19125
0
    {
19126
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
19127
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
19128
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
19129
0
    };
19130
19131
    // Elements rendered manually via ImDrawList API are not clipped automatically.
19132
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
19133
0
    Dummy(board_max - board_min);
19134
0
    if (!IsItemVisible())
19135
0
        return;
19136
0
    draw_list->PushClipRect(board_min, board_max, true);
19137
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
19138
0
    {
19139
0
        const KeyLayoutData* key_data = &keys_to_display[n];
19140
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
19141
0
        ImVec2 key_max = key_min + key_size;
19142
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
19143
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
19144
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
19145
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
19146
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
19147
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
19148
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
19149
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
19150
0
        if (IsKeyDown(key_data->Key))
19151
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
19152
0
    }
19153
0
    draw_list->PopClipRect();
19154
0
}
19155
19156
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
19157
void ImGui::DebugTextEncoding(const char* str)
19158
0
{
19159
0
    Text("Text: \"%s\"", str);
19160
0
    if (!BeginTable("##DebugTextEncoding", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_Resizable))
19161
0
        return;
19162
0
    TableSetupColumn("Offset");
19163
0
    TableSetupColumn("UTF-8");
19164
0
    TableSetupColumn("Glyph");
19165
0
    TableSetupColumn("Codepoint");
19166
0
    TableHeadersRow();
19167
0
    for (const char* p = str; *p != 0; )
19168
0
    {
19169
0
        unsigned int c;
19170
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
19171
0
        TableNextColumn();
19172
0
        Text("%d", (int)(p - str));
19173
0
        TableNextColumn();
19174
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
19175
0
        {
19176
0
            if (byte_index > 0)
19177
0
                SameLine();
19178
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
19179
0
        }
19180
0
        TableNextColumn();
19181
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
19182
0
            TextUnformatted(p, p + c_utf8_len);
19183
0
        else
19184
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
19185
0
        TableNextColumn();
19186
0
        Text("U+%04X", (int)c);
19187
0
        p += c_utf8_len;
19188
0
    }
19189
0
    EndTable();
19190
0
}
19191
19192
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
19193
static void MetricsHelpMarker(const char* desc)
19194
0
{
19195
0
    ImGui::TextDisabled("(?)");
19196
0
    if (ImGui::BeginItemTooltip())
19197
0
    {
19198
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
19199
0
        ImGui::TextUnformatted(desc);
19200
0
        ImGui::PopTextWrapPos();
19201
0
        ImGui::EndTooltip();
19202
0
    }
19203
0
}
19204
19205
// [DEBUG] List fonts in a font atlas and display its texture
19206
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
19207
0
{
19208
0
    for (int i = 0; i < atlas->Fonts.Size; i++)
19209
0
    {
19210
0
        ImFont* font = atlas->Fonts[i];
19211
0
        PushID(font);
19212
0
        DebugNodeFont(font);
19213
0
        PopID();
19214
0
    }
19215
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
19216
0
    {
19217
0
        ImGuiContext& g = *GImGui;
19218
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19219
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
19220
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
19221
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
19222
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
19223
0
        TreePop();
19224
0
    }
19225
0
}
19226
19227
void ImGui::ShowMetricsWindow(bool* p_open)
19228
0
{
19229
0
    ImGuiContext& g = *GImGui;
19230
0
    ImGuiIO& io = g.IO;
19231
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19232
0
    if (cfg->ShowDebugLog)
19233
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
19234
0
    if (cfg->ShowStackTool)
19235
0
        ShowStackToolWindow(&cfg->ShowStackTool);
19236
19237
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
19238
0
    {
19239
0
        End();
19240
0
        return;
19241
0
    }
19242
19243
    // Basic info
19244
0
    Text("Dear ImGui %s", GetVersion());
19245
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
19246
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
19247
0
    Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
19248
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
19249
19250
0
    Separator();
19251
19252
    // Debugging enums
19253
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
19254
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
19255
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
19256
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
19257
0
    if (cfg->ShowWindowsRectsType < 0)
19258
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
19259
0
    if (cfg->ShowTablesRectsType < 0)
19260
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
19261
19262
0
    struct Funcs
19263
0
    {
19264
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
19265
0
        {
19266
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
19267
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
19268
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
19269
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
19270
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
19271
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
19272
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
19273
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
19274
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
19275
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
19276
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
19277
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
19278
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
19279
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
19280
0
            IM_ASSERT(0);
19281
0
            return ImRect();
19282
0
        }
19283
19284
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
19285
0
        {
19286
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
19287
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
19288
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
19289
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
19290
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
19291
0
            else if (rect_type == WRT_Content)              { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
19292
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
19293
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
19294
0
            IM_ASSERT(0);
19295
0
            return ImRect();
19296
0
        }
19297
0
    };
19298
19299
    // Tools
19300
0
    if (TreeNode("Tools"))
19301
0
    {
19302
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
19303
0
        SameLine();
19304
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
19305
0
        if (show_encoding_viewer)
19306
0
        {
19307
0
            static char buf[100] = "";
19308
0
            SetNextItemWidth(-FLT_MIN);
19309
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
19310
0
            if (buf[0] != 0)
19311
0
                DebugTextEncoding(buf);
19312
0
            TreePop();
19313
0
        }
19314
19315
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
19316
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
19317
0
            DebugStartItemPicker();
19318
0
        SameLine();
19319
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
19320
19321
        // Stack Tool is your best friend!
19322
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
19323
0
        SameLine();
19324
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
19325
19326
        // Stack Tool is your best friend!
19327
0
        Checkbox("Show Stack Tool", &cfg->ShowStackTool);
19328
0
        SameLine();
19329
0
        MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
19330
19331
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
19332
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
19333
0
        SameLine();
19334
0
        SetNextItemWidth(GetFontSize() * 12);
19335
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
19336
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
19337
0
        {
19338
0
            BulletText("'%s':", g.NavWindow->Name);
19339
0
            Indent();
19340
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
19341
0
            {
19342
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
19343
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
19344
0
            }
19345
0
            Unindent();
19346
0
        }
19347
19348
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
19349
0
        SameLine();
19350
0
        SetNextItemWidth(GetFontSize() * 12);
19351
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
19352
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
19353
0
        {
19354
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19355
0
            {
19356
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19357
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
19358
0
                    continue;
19359
19360
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
19361
0
                if (IsItemHovered())
19362
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19363
0
                Indent();
19364
0
                char buf[128];
19365
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
19366
0
                {
19367
0
                    if (rect_n >= TRT_ColumnsRect)
19368
0
                    {
19369
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
19370
0
                            continue;
19371
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19372
0
                        {
19373
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
19374
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
19375
0
                            Selectable(buf);
19376
0
                            if (IsItemHovered())
19377
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19378
0
                        }
19379
0
                    }
19380
0
                    else
19381
0
                    {
19382
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
19383
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
19384
0
                        Selectable(buf);
19385
0
                        if (IsItemHovered())
19386
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
19387
0
                    }
19388
0
                }
19389
0
                Unindent();
19390
0
            }
19391
0
        }
19392
19393
0
        Checkbox("Debug Begin/BeginChild return value", &io.ConfigDebugBeginReturnValueLoop);
19394
0
        SameLine();
19395
0
        MetricsHelpMarker("Some calls to Begin()/BeginChild() will return false.\n\nWill cycle through window depths then repeat. Windows should be flickering while running.");
19396
19397
0
        TreePop();
19398
0
    }
19399
19400
    // Windows
19401
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
19402
0
    {
19403
        //SetNextItemOpen(true, ImGuiCond_Once);
19404
0
        DebugNodeWindowsList(&g.Windows, "By display order");
19405
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
19406
0
        if (TreeNode("By submission order (begin stack)"))
19407
0
        {
19408
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
19409
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
19410
0
            temp_buffer.resize(0);
19411
0
            for (int i = 0; i < g.Windows.Size; i++)
19412
0
                if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
19413
0
                    temp_buffer.push_back(g.Windows[i]);
19414
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
19415
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
19416
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
19417
0
            TreePop();
19418
0
        }
19419
19420
0
        TreePop();
19421
0
    }
19422
19423
    // DrawLists
19424
0
    int drawlist_count = 0;
19425
0
    for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
19426
0
        drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
19427
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
19428
0
    {
19429
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
19430
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
19431
0
        for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
19432
0
        {
19433
0
            ImGuiViewportP* viewport = g.Viewports[viewport_i];
19434
0
            bool viewport_has_drawlist = false;
19435
0
            for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
19436
0
                for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
19437
0
                {
19438
0
                    if (!viewport_has_drawlist)
19439
0
                        Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
19440
0
                    viewport_has_drawlist = true;
19441
0
                    DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
19442
0
                }
19443
0
        }
19444
0
        TreePop();
19445
0
    }
19446
19447
    // Viewports
19448
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
19449
0
    {
19450
0
        Indent(GetTreeNodeToLabelSpacing());
19451
0
        RenderViewportsThumbnails();
19452
0
        Unindent(GetTreeNodeToLabelSpacing());
19453
19454
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
19455
0
        SameLine();
19456
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
19457
0
        if (open)
19458
0
        {
19459
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
19460
0
            {
19461
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
19462
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
19463
0
                    i, mon.DpiScale * 100.0f,
19464
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
19465
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
19466
0
            }
19467
0
            TreePop();
19468
0
        }
19469
19470
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19471
0
        if (TreeNode("Inferred Z order (front-to-back)"))
19472
0
        {
19473
0
            static ImVector<ImGuiViewportP*> viewports;
19474
0
            viewports.resize(g.Viewports.Size);
19475
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
19476
0
            if (viewports.Size > 1)
19477
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByLastFocusedStampCount);
19478
0
            for (ImGuiViewportP* viewport : viewports)
19479
0
                BulletText("Viewport #%d, ID: 0x%08X, LastFocused = %08d, PlatformFocused = %s, Window: \"%s\"",
19480
0
                    viewport->Idx, viewport->ID, viewport->LastFocusedStampCount,
19481
0
                    (g.PlatformIO.Platform_GetWindowFocus && viewport->PlatformWindowCreated) ? (g.PlatformIO.Platform_GetWindowFocus(viewport) ? "1" : "0") : "N/A",
19482
0
                    viewport->Window ? viewport->Window->Name : "N/A");
19483
0
            TreePop();
19484
0
        }
19485
0
        for (int i = 0; i < g.Viewports.Size; i++)
19486
0
            DebugNodeViewport(g.Viewports[i]);
19487
0
        TreePop();
19488
0
    }
19489
19490
    // Details for Popups
19491
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
19492
0
    {
19493
0
        for (int i = 0; i < g.OpenPopupStack.Size; i++)
19494
0
        {
19495
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
19496
0
            const ImGuiPopupData* popup_data = &g.OpenPopupStack[i];
19497
0
            ImGuiWindow* window = popup_data->Window;
19498
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
19499
0
                popup_data->PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
19500
0
                popup_data->BackupNavWindow ? popup_data->BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
19501
0
        }
19502
0
        TreePop();
19503
0
    }
19504
19505
    // Details for TabBars
19506
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
19507
0
    {
19508
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
19509
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
19510
0
            {
19511
0
                PushID(tab_bar);
19512
0
                DebugNodeTabBar(tab_bar, "TabBar");
19513
0
                PopID();
19514
0
            }
19515
0
        TreePop();
19516
0
    }
19517
19518
    // Details for Tables
19519
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
19520
0
    {
19521
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
19522
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
19523
0
                DebugNodeTable(table);
19524
0
        TreePop();
19525
0
    }
19526
19527
    // Details for Fonts
19528
0
    ImFontAtlas* atlas = g.IO.Fonts;
19529
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
19530
0
    {
19531
0
        ShowFontAtlas(atlas);
19532
0
        TreePop();
19533
0
    }
19534
19535
    // Details for InputText
19536
0
    if (TreeNode("InputText"))
19537
0
    {
19538
0
        DebugNodeInputTextState(&g.InputTextState);
19539
0
        TreePop();
19540
0
    }
19541
19542
    // Details for Docking
19543
0
#ifdef IMGUI_HAS_DOCK
19544
0
    if (TreeNode("Docking"))
19545
0
    {
19546
0
        static bool root_nodes_only = true;
19547
0
        ImGuiDockContext* dc = &g.DockContext;
19548
0
        Checkbox("List root nodes", &root_nodes_only);
19549
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19550
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19551
0
        SameLine();
19552
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19553
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19554
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19555
0
                if (!root_nodes_only || node->IsRootNode())
19556
0
                    DebugNodeDockNode(node, "Node");
19557
0
        TreePop();
19558
0
    }
19559
0
#endif // #ifdef IMGUI_HAS_DOCK
19560
19561
    // Settings
19562
0
    if (TreeNode("Settings"))
19563
0
    {
19564
0
        if (SmallButton("Clear"))
19565
0
            ClearIniSettings();
19566
0
        SameLine();
19567
0
        if (SmallButton("Save to memory"))
19568
0
            SaveIniSettingsToMemory();
19569
0
        SameLine();
19570
0
        if (SmallButton("Save to disk"))
19571
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19572
0
        SameLine();
19573
0
        if (g.IO.IniFilename)
19574
0
            Text("\"%s\"", g.IO.IniFilename);
19575
0
        else
19576
0
            TextUnformatted("<NULL>");
19577
0
        Checkbox("io.ConfigDebugIniSettings", &io.ConfigDebugIniSettings);
19578
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19579
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19580
0
        {
19581
0
            for (int n = 0; n < g.SettingsHandlers.Size; n++)
19582
0
                BulletText("\"%s\"", g.SettingsHandlers[n].TypeName);
19583
0
            TreePop();
19584
0
        }
19585
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19586
0
        {
19587
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19588
0
                DebugNodeWindowSettings(settings);
19589
0
            TreePop();
19590
0
        }
19591
19592
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19593
0
        {
19594
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19595
0
                DebugNodeTableSettings(settings);
19596
0
            TreePop();
19597
0
        }
19598
19599
0
#ifdef IMGUI_HAS_DOCK
19600
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19601
0
        {
19602
0
            ImGuiDockContext* dc = &g.DockContext;
19603
0
            Text("In SettingsWindows:");
19604
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19605
0
                if (settings->DockId != 0)
19606
0
                    BulletText("Window '%s' -> DockId %08X DockOrder=%d", settings->GetName(), settings->DockId, settings->DockOrder);
19607
0
            Text("In SettingsNodes:");
19608
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19609
0
            {
19610
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19611
0
                const char* selected_tab_name = NULL;
19612
0
                if (settings->SelectedTabId)
19613
0
                {
19614
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19615
0
                        selected_tab_name = window->Name;
19616
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
19617
0
                        selected_tab_name = window_settings->GetName();
19618
0
                }
19619
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19620
0
            }
19621
0
            TreePop();
19622
0
        }
19623
0
#endif // #ifdef IMGUI_HAS_DOCK
19624
19625
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19626
0
        {
19627
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19628
0
            TreePop();
19629
0
        }
19630
0
        TreePop();
19631
0
    }
19632
19633
0
    if (TreeNode("Inputs"))
19634
0
    {
19635
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19636
0
        {
19637
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19638
            // User code should never have to go through such hoops! You can generally iterate between ImGuiKey_NamedKey_BEGIN and ImGuiKey_NamedKey_END.
19639
0
            Indent();
19640
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19641
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19642
#else
19643
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19644
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19645
#endif
19646
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19647
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19648
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19649
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19650
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19651
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19652
0
            Unindent();
19653
0
        }
19654
19655
0
        Text("MOUSE STATE");
19656
0
        {
19657
0
            Indent();
19658
0
            if (IsMousePosValid())
19659
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19660
0
            else
19661
0
                Text("Mouse pos: <INVALID>");
19662
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19663
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19664
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19665
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19666
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19667
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19668
0
            Text("MouseStationaryTimer: %.2f", g.MouseStationaryTimer);
19669
0
            Text("Mouse source: %s", GetMouseSourceName(io.MouseSource));
19670
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19671
0
            Unindent();
19672
0
        }
19673
19674
0
        Text("MOUSE WHEELING");
19675
0
        {
19676
0
            Indent();
19677
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19678
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19679
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19680
0
            Unindent();
19681
0
        }
19682
19683
0
        Text("KEY OWNERS");
19684
0
        {
19685
0
            Indent();
19686
0
            if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19687
0
            {
19688
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19689
0
                {
19690
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(&g, key);
19691
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19692
0
                        continue;
19693
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19694
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19695
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19696
0
                }
19697
0
                EndListBox();
19698
0
            }
19699
0
            Unindent();
19700
0
        }
19701
0
        Text("SHORTCUT ROUTING");
19702
0
        {
19703
0
            Indent();
19704
0
            if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19705
0
            {
19706
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19707
0
                {
19708
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19709
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
19710
0
                    {
19711
0
                        char key_chord_name[64];
19712
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
19713
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
19714
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
19715
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
19716
0
                        idx = routing_data->NextEntryIndex;
19717
0
                    }
19718
0
                }
19719
0
                EndListBox();
19720
0
            }
19721
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19722
0
            Unindent();
19723
0
        }
19724
0
        TreePop();
19725
0
    }
19726
19727
0
    if (TreeNode("Internal state"))
19728
0
    {
19729
0
        Text("WINDOWING");
19730
0
        Indent();
19731
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
19732
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
19733
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
19734
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
19735
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
19736
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19737
0
        Unindent();
19738
19739
0
        Text("ITEMS");
19740
0
        Indent();
19741
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
19742
0
        DebugLocateItemOnHover(g.ActiveId);
19743
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
19744
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19745
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
19746
0
        Text("HoverItemDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverItemDelayId, g.HoverItemDelayTimer, g.HoverItemDelayClearTimer);
19747
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
19748
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
19749
0
        Unindent();
19750
19751
0
        Text("NAV,FOCUS");
19752
0
        Indent();
19753
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
19754
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
19755
0
        DebugLocateItemOnHover(g.NavId);
19756
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
19757
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
19758
0
        Text("NavActivateId/DownId/PressedId: %08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId);
19759
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
19760
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
19761
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
19762
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
19763
0
        Unindent();
19764
19765
0
        TreePop();
19766
0
    }
19767
19768
    // Overlay: Display windows Rectangles and Begin Order
19769
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
19770
0
    {
19771
0
        for (int n = 0; n < g.Windows.Size; n++)
19772
0
        {
19773
0
            ImGuiWindow* window = g.Windows[n];
19774
0
            if (!window->WasActive)
19775
0
                continue;
19776
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
19777
0
            if (cfg->ShowWindowsRects)
19778
0
            {
19779
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
19780
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19781
0
            }
19782
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
19783
0
            {
19784
0
                char buf[32];
19785
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
19786
0
                float font_size = GetFontSize();
19787
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
19788
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
19789
0
            }
19790
0
        }
19791
0
    }
19792
19793
    // Overlay: Display Tables Rectangles
19794
0
    if (cfg->ShowTablesRects)
19795
0
    {
19796
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19797
0
        {
19798
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19799
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
19800
0
                continue;
19801
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
19802
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
19803
0
            {
19804
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19805
0
                {
19806
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
19807
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
19808
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
19809
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
19810
0
                }
19811
0
            }
19812
0
            else
19813
0
            {
19814
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
19815
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19816
0
            }
19817
0
        }
19818
0
    }
19819
19820
0
#ifdef IMGUI_HAS_DOCK
19821
    // Overlay: Display Docking info
19822
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
19823
0
    {
19824
0
        char buf[64] = "";
19825
0
        char* p = buf;
19826
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
19827
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19828
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
19829
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
19830
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
19831
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
19832
0
        int depth = DockNodeGetDepth(node);
19833
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
19834
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
19835
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
19836
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
19837
0
    }
19838
0
#endif // #ifdef IMGUI_HAS_DOCK
19839
19840
0
    End();
19841
0
}
19842
19843
// [DEBUG] Display contents of Columns
19844
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
19845
0
{
19846
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
19847
0
        return;
19848
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
19849
0
    for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
19850
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
19851
0
    TreePop();
19852
0
}
19853
19854
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
19855
0
{
19856
0
    using namespace ImGui;
19857
0
    PushID(label);
19858
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
19859
0
    Text("%s:", label);
19860
0
    if (!enabled)
19861
0
        BeginDisabled();
19862
0
    CheckboxFlags("NoSplit", p_flags, ImGuiDockNodeFlags_NoSplit);
19863
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
19864
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
19865
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
19866
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
19867
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
19868
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
19869
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
19870
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking);
19871
0
    CheckboxFlags("NoDockingSplitMe", p_flags, ImGuiDockNodeFlags_NoDockingSplitMe);
19872
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
19873
0
    CheckboxFlags("NoDockingOverMe", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
19874
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
19875
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
19876
0
    if (!enabled)
19877
0
        EndDisabled();
19878
0
    PopStyleVar();
19879
0
    PopID();
19880
0
}
19881
19882
// [DEBUG] Display contents of ImDockNode
19883
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
19884
0
{
19885
0
    ImGuiContext& g = *GImGui;
19886
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
19887
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
19888
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19889
0
    bool open;
19890
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19891
0
    if (node->Windows.Size > 0)
19892
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19893
0
    else
19894
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19895
0
    if (!is_alive) { PopStyleColor(); }
19896
0
    if (is_active && IsItemHovered())
19897
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
19898
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
19899
0
    if (open)
19900
0
    {
19901
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
19902
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
19903
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
19904
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
19905
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
19906
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
19907
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
19908
0
        BulletText("Misc:%s%s%s%s%s%s%s",
19909
0
            node->IsDockSpace() ? " IsDockSpace" : "",
19910
0
            node->IsCentralNode() ? " IsCentralNode" : "",
19911
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
19912
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
19913
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
19914
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
19915
0
        {
19916
0
            if (BeginTable("flags", 4))
19917
0
            {
19918
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
19919
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
19920
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
19921
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
19922
0
                EndTable();
19923
0
            }
19924
0
            TreePop();
19925
0
        }
19926
0
        if (node->ParentNode)
19927
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
19928
0
        if (node->ChildNodes[0])
19929
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
19930
0
        if (node->ChildNodes[1])
19931
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
19932
0
        if (node->TabBar)
19933
0
            DebugNodeTabBar(node->TabBar, "TabBar");
19934
0
        DebugNodeWindowsList(&node->Windows, "Windows");
19935
19936
0
        TreePop();
19937
0
    }
19938
0
}
19939
19940
// [DEBUG] Display contents of ImDrawList
19941
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
19942
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
19943
0
{
19944
0
    ImGuiContext& g = *GImGui;
19945
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19946
0
    int cmd_count = draw_list->CmdBuffer.Size;
19947
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
19948
0
        cmd_count--;
19949
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
19950
0
    if (draw_list == GetWindowDrawList())
19951
0
    {
19952
0
        SameLine();
19953
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
19954
0
        if (node_open)
19955
0
            TreePop();
19956
0
        return;
19957
0
    }
19958
19959
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
19960
0
    if (window && IsItemHovered() && fg_draw_list)
19961
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19962
0
    if (!node_open)
19963
0
        return;
19964
19965
0
    if (window && !window->WasActive)
19966
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
19967
19968
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
19969
0
    {
19970
0
        if (pcmd->UserCallback)
19971
0
        {
19972
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
19973
0
            continue;
19974
0
        }
19975
19976
0
        char buf[300];
19977
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
19978
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
19979
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
19980
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
19981
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
19982
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
19983
0
        if (!pcmd_node_open)
19984
0
            continue;
19985
19986
        // Calculate approximate coverage area (touched pixel count)
19987
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
19988
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
19989
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
19990
0
        float total_area = 0.0f;
19991
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
19992
0
        {
19993
0
            ImVec2 triangle[3];
19994
0
            for (int n = 0; n < 3; n++, idx_n++)
19995
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
19996
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
19997
0
        }
19998
19999
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
20000
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
20001
0
        Selectable(buf);
20002
0
        if (IsItemHovered() && fg_draw_list)
20003
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
20004
20005
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
20006
0
        ImGuiListClipper clipper;
20007
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
20008
0
        while (clipper.Step())
20009
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
20010
0
            {
20011
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
20012
0
                ImVec2 triangle[3];
20013
0
                for (int n = 0; n < 3; n++, idx_i++)
20014
0
                {
20015
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
20016
0
                    triangle[n] = v.pos;
20017
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
20018
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
20019
0
                }
20020
20021
0
                Selectable(buf, false);
20022
0
                if (fg_draw_list && IsItemHovered())
20023
0
                {
20024
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
20025
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20026
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
20027
0
                    fg_draw_list->Flags = backup_flags;
20028
0
                }
20029
0
            }
20030
0
        TreePop();
20031
0
    }
20032
0
    TreePop();
20033
0
}
20034
20035
// [DEBUG] Display mesh/aabb of a ImDrawCmd
20036
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
20037
0
{
20038
0
    IM_ASSERT(show_mesh || show_aabb);
20039
20040
    // Draw wire-frame version of all triangles
20041
0
    ImRect clip_rect = draw_cmd->ClipRect;
20042
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
20043
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
20044
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
20045
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
20046
0
    {
20047
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
20048
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
20049
20050
0
        ImVec2 triangle[3];
20051
0
        for (int n = 0; n < 3; n++, idx_n++)
20052
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
20053
0
        if (show_mesh)
20054
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
20055
0
    }
20056
    // Draw bounding boxes
20057
0
    if (show_aabb)
20058
0
    {
20059
0
        out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
20060
0
        out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
20061
0
    }
20062
0
    out_draw_list->Flags = backup_flags;
20063
0
}
20064
20065
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
20066
void ImGui::DebugNodeFont(ImFont* font)
20067
0
{
20068
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
20069
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
20070
0
    SameLine();
20071
0
    if (SmallButton("Set as default"))
20072
0
        GetIO().FontDefault = font;
20073
0
    if (!opened)
20074
0
        return;
20075
20076
    // Display preview text
20077
0
    PushFont(font);
20078
0
    Text("The quick brown fox jumps over the lazy dog");
20079
0
    PopFont();
20080
20081
    // Display details
20082
0
    SetNextItemWidth(GetFontSize() * 8);
20083
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
20084
0
    SameLine(); MetricsHelpMarker(
20085
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
20086
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
20087
0
        "You may oversample them to get some flexibility with scaling. "
20088
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
20089
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
20090
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
20091
0
    char c_str[5];
20092
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
20093
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
20094
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
20095
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
20096
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
20097
0
        if (font->ConfigData)
20098
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
20099
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
20100
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
20101
20102
    // Display all glyphs of the fonts in separate pages of 256 characters
20103
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
20104
0
    {
20105
0
        ImDrawList* draw_list = GetWindowDrawList();
20106
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
20107
0
        const float cell_size = font->FontSize * 1;
20108
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
20109
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
20110
0
        {
20111
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
20112
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
20113
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
20114
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
20115
0
            {
20116
0
                base += 4096 - 256;
20117
0
                continue;
20118
0
            }
20119
20120
0
            int count = 0;
20121
0
            for (unsigned int n = 0; n < 256; n++)
20122
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
20123
0
                    count++;
20124
0
            if (count <= 0)
20125
0
                continue;
20126
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
20127
0
                continue;
20128
20129
            // Draw a 16x16 grid of glyphs
20130
0
            ImVec2 base_pos = GetCursorScreenPos();
20131
0
            for (unsigned int n = 0; n < 256; n++)
20132
0
            {
20133
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
20134
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
20135
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
20136
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
20137
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
20138
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
20139
0
                if (!glyph)
20140
0
                    continue;
20141
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
20142
0
                if (IsMouseHoveringRect(cell_p1, cell_p2) && BeginTooltip())
20143
0
                {
20144
0
                    DebugNodeFontGlyph(font, glyph);
20145
0
                    EndTooltip();
20146
0
                }
20147
0
            }
20148
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
20149
0
            TreePop();
20150
0
        }
20151
0
        TreePop();
20152
0
    }
20153
0
    TreePop();
20154
0
}
20155
20156
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
20157
0
{
20158
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
20159
0
    Separator();
20160
0
    Text("Visible: %d", glyph->Visible);
20161
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
20162
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
20163
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
20164
0
}
20165
20166
// [DEBUG] Display contents of ImGuiStorage
20167
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
20168
0
{
20169
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
20170
0
        return;
20171
0
    for (int n = 0; n < storage->Data.Size; n++)
20172
0
    {
20173
0
        const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
20174
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
20175
0
    }
20176
0
    TreePop();
20177
0
}
20178
20179
// [DEBUG] Display contents of ImGuiTabBar
20180
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
20181
0
{
20182
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
20183
0
    char buf[256];
20184
0
    char* p = buf;
20185
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
20186
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
20187
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s  {", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
20188
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
20189
0
    {
20190
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20191
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
20192
0
    }
20193
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
20194
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20195
0
    bool open = TreeNode(label, "%s", buf);
20196
0
    if (!is_active) { PopStyleColor(); }
20197
0
    if (is_active && IsItemHovered())
20198
0
    {
20199
0
        ImDrawList* draw_list = GetForegroundDrawList();
20200
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
20201
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20202
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
20203
0
    }
20204
0
    if (open)
20205
0
    {
20206
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
20207
0
        {
20208
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
20209
0
            PushID(tab);
20210
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
20211
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
20212
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
20213
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
20214
0
            PopID();
20215
0
        }
20216
0
        TreePop();
20217
0
    }
20218
0
}
20219
20220
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
20221
0
{
20222
0
    SetNextItemOpen(true, ImGuiCond_Once);
20223
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
20224
0
    {
20225
0
        ImGuiWindowFlags flags = viewport->Flags;
20226
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
20227
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
20228
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
20229
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
20230
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
20231
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
20232
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
20233
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
20234
0
            (flags & ImGuiViewportFlags_IsMinimized) ? " IsMinimized" : "",
20235
0
            (flags & ImGuiViewportFlags_IsFocused) ? " IsFocused" : "",
20236
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
20237
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
20238
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
20239
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
20240
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
20241
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
20242
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
20243
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
20244
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
20245
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
20246
0
        for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
20247
0
            for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
20248
0
                DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
20249
0
        TreePop();
20250
0
    }
20251
0
}
20252
20253
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
20254
0
{
20255
0
    if (window == NULL)
20256
0
    {
20257
0
        BulletText("%s: NULL", label);
20258
0
        return;
20259
0
    }
20260
20261
0
    ImGuiContext& g = *GImGui;
20262
0
    const bool is_active = window->WasActive;
20263
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
20264
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
20265
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
20266
0
    if (!is_active) { PopStyleColor(); }
20267
0
    if (IsItemHovered() && is_active)
20268
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
20269
0
    if (!open)
20270
0
        return;
20271
20272
0
    if (window->MemoryCompacted)
20273
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
20274
20275
0
    ImGuiWindowFlags flags = window->Flags;
20276
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
20277
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
20278
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
20279
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
20280
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
20281
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
20282
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
20283
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
20284
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
20285
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
20286
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20287
0
    {
20288
0
        ImRect r = window->NavRectRel[layer];
20289
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
20290
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
20291
0
        else
20292
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
20293
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
20294
0
    }
20295
0
    const ImVec2* pr = window->NavPreferredScoringPosRel;
20296
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
20297
0
        BulletText("NavPreferredScoringPosRel[%d] = {%.1f,%.1f)", layer, (pr[layer].x == FLT_MAX ? -99999.0f : pr[layer].x), (pr[layer].y == FLT_MAX ? -99999.0f : pr[layer].y)); // Display as 99999.0f so it looks neater.
20298
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
20299
20300
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
20301
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
20302
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
20303
0
    if (window->DockNode || window->DockNodeAsHost)
20304
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
20305
20306
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
20307
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
20308
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
20309
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
20310
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
20311
0
    {
20312
0
        for (int n = 0; n < window->ColumnsStorage.Size; n++)
20313
0
            DebugNodeColumns(&window->ColumnsStorage[n]);
20314
0
        TreePop();
20315
0
    }
20316
0
    DebugNodeStorage(&window->StateStorage, "Storage");
20317
0
    TreePop();
20318
0
}
20319
20320
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
20321
0
{
20322
0
    if (settings->WantDelete)
20323
0
        BeginDisabled();
20324
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
20325
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
20326
0
    if (settings->WantDelete)
20327
0
        EndDisabled();
20328
0
}
20329
20330
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
20331
0
{
20332
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
20333
0
        return;
20334
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
20335
0
    {
20336
0
        PushID((*windows)[i]);
20337
0
        DebugNodeWindow((*windows)[i], "Window");
20338
0
        PopID();
20339
0
    }
20340
0
    TreePop();
20341
0
}
20342
20343
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
20344
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
20345
0
{
20346
0
    for (int i = 0; i < windows_size; i++)
20347
0
    {
20348
0
        ImGuiWindow* window = windows[i];
20349
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
20350
0
            continue;
20351
0
        char buf[20];
20352
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
20353
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
20354
0
        DebugNodeWindow(window, buf);
20355
0
        Indent();
20356
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
20357
0
        Unindent();
20358
0
    }
20359
0
}
20360
20361
//-----------------------------------------------------------------------------
20362
// [SECTION] DEBUG LOG WINDOW
20363
//-----------------------------------------------------------------------------
20364
20365
void ImGui::DebugLog(const char* fmt, ...)
20366
0
{
20367
0
    va_list args;
20368
0
    va_start(args, fmt);
20369
0
    DebugLogV(fmt, args);
20370
0
    va_end(args);
20371
0
}
20372
20373
void ImGui::DebugLogV(const char* fmt, va_list args)
20374
0
{
20375
0
    ImGuiContext& g = *GImGui;
20376
0
    const int old_size = g.DebugLogBuf.size();
20377
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
20378
0
    g.DebugLogBuf.appendfv(fmt, args);
20379
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
20380
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
20381
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
20382
0
}
20383
20384
void ImGui::ShowDebugLogWindow(bool* p_open)
20385
0
{
20386
0
    ImGuiContext& g = *GImGui;
20387
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20388
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
20389
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
20390
0
    {
20391
0
        End();
20392
0
        return;
20393
0
    }
20394
20395
0
    CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
20396
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
20397
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
20398
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
20399
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
20400
0
    SameLine(); if (CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper)) { g.DebugLogClipperAutoDisableFrames = 2; } if (IsItemHovered()) SetTooltip("Clipper log auto-disabled after 2 frames");
20401
    //SameLine(); CheckboxFlags("Selection", &g.DebugLogFlags, ImGuiDebugLogFlags_EventSelection);
20402
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
20403
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
20404
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
20405
20406
0
    if (SmallButton("Clear"))
20407
0
    {
20408
0
        g.DebugLogBuf.clear();
20409
0
        g.DebugLogIndex.clear();
20410
0
    }
20411
0
    SameLine();
20412
0
    if (SmallButton("Copy"))
20413
0
        SetClipboardText(g.DebugLogBuf.c_str());
20414
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
20415
20416
0
    ImGuiListClipper clipper;
20417
0
    clipper.Begin(g.DebugLogIndex.size());
20418
0
    while (clipper.Step())
20419
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
20420
0
        {
20421
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
20422
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
20423
0
            TextUnformatted(line_begin, line_end);
20424
0
            ImRect text_rect = g.LastItemData.Rect;
20425
0
            if (IsItemHovered())
20426
0
                for (const char* p = line_begin; p <= line_end - 10; p++)
20427
0
                {
20428
0
                    ImGuiID id = 0;
20429
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
20430
0
                        continue;
20431
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
20432
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
20433
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
20434
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
20435
0
                        DebugLocateItemOnHover(id);
20436
0
                    p += 10;
20437
0
                }
20438
0
        }
20439
0
    if (GetScrollY() >= GetScrollMaxY())
20440
0
        SetScrollHereY(1.0f);
20441
0
    EndChild();
20442
20443
0
    End();
20444
0
}
20445
20446
//-----------------------------------------------------------------------------
20447
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
20448
//-----------------------------------------------------------------------------
20449
20450
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
20451
20452
void ImGui::DebugLocateItem(ImGuiID target_id)
20453
0
{
20454
0
    ImGuiContext& g = *GImGui;
20455
0
    g.DebugLocateId = target_id;
20456
0
    g.DebugLocateFrames = 2;
20457
0
}
20458
20459
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
20460
0
{
20461
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
20462
0
        return;
20463
0
    ImGuiContext& g = *GImGui;
20464
0
    DebugLocateItem(target_id);
20465
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
20466
0
}
20467
20468
void ImGui::DebugLocateItemResolveWithLastItem()
20469
0
{
20470
0
    ImGuiContext& g = *GImGui;
20471
0
    ImGuiLastItemData item_data = g.LastItemData;
20472
0
    g.DebugLocateId = 0;
20473
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
20474
0
    ImRect r = item_data.Rect;
20475
0
    r.Expand(3.0f);
20476
0
    ImVec2 p1 = g.IO.MousePos;
20477
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
20478
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
20479
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
20480
0
}
20481
20482
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
20483
void ImGui::UpdateDebugToolItemPicker()
20484
18.0k
{
20485
18.0k
    ImGuiContext& g = *GImGui;
20486
18.0k
    g.DebugItemPickerBreakId = 0;
20487
18.0k
    if (!g.DebugItemPickerActive)
20488
18.0k
        return;
20489
20490
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20491
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
20492
0
    if (IsKeyPressed(ImGuiKey_Escape))
20493
0
        g.DebugItemPickerActive = false;
20494
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
20495
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
20496
0
    {
20497
0
        g.DebugItemPickerBreakId = hovered_id;
20498
0
        g.DebugItemPickerActive = false;
20499
0
    }
20500
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
20501
0
        if (change_mapping && IsMouseClicked(mouse_button))
20502
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
20503
0
    SetNextWindowBgAlpha(0.70f);
20504
0
    if (!BeginTooltip())
20505
0
        return;
20506
0
    Text("HoveredId: 0x%08X", hovered_id);
20507
0
    Text("Press ESC to abort picking.");
20508
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
20509
0
    if (change_mapping)
20510
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
20511
0
    else
20512
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
20513
0
    EndTooltip();
20514
0
}
20515
20516
// [DEBUG] Stack Tool: update queries. Called by NewFrame()
20517
void ImGui::UpdateDebugToolStackQueries()
20518
18.0k
{
20519
18.0k
    ImGuiContext& g = *GImGui;
20520
18.0k
    ImGuiStackTool* tool = &g.DebugStackTool;
20521
20522
    // Clear hook when stack tool is not visible
20523
18.0k
    g.DebugHookIdInfo = 0;
20524
18.0k
    if (g.FrameCount != tool->LastActiveFrame + 1)
20525
18.0k
        return;
20526
20527
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
20528
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
20529
2
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
20530
2
    if (tool->QueryId != query_id)
20531
0
    {
20532
0
        tool->QueryId = query_id;
20533
0
        tool->StackLevel = -1;
20534
0
        tool->Results.resize(0);
20535
0
    }
20536
2
    if (query_id == 0)
20537
2
        return;
20538
20539
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
20540
0
    int stack_level = tool->StackLevel;
20541
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20542
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
20543
0
            tool->StackLevel++;
20544
20545
    // Update hook
20546
0
    stack_level = tool->StackLevel;
20547
0
    if (stack_level == -1)
20548
0
        g.DebugHookIdInfo = query_id;
20549
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20550
0
    {
20551
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20552
0
        tool->Results[stack_level].QueryFrameCount++;
20553
0
    }
20554
0
}
20555
20556
// [DEBUG] Stack tool: hooks called by GetID() family functions
20557
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20558
0
{
20559
0
    ImGuiContext& g = *GImGui;
20560
0
    ImGuiWindow* window = g.CurrentWindow;
20561
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20562
20563
    // Step 0: stack query
20564
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20565
0
    if (tool->StackLevel == -1)
20566
0
    {
20567
0
        tool->StackLevel++;
20568
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20569
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20570
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20571
0
        return;
20572
0
    }
20573
20574
    // Step 1+: query for individual level
20575
0
    IM_ASSERT(tool->StackLevel >= 0);
20576
0
    if (tool->StackLevel != window->IDStack.Size)
20577
0
        return;
20578
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20579
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20580
20581
0
    switch (data_type)
20582
0
    {
20583
0
    case ImGuiDataType_S32:
20584
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20585
0
        break;
20586
0
    case ImGuiDataType_String:
20587
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20588
0
        break;
20589
0
    case ImGuiDataType_Pointer:
20590
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20591
0
        break;
20592
0
    case ImGuiDataType_ID:
20593
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20594
0
            return;
20595
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20596
0
        break;
20597
0
    default:
20598
0
        IM_ASSERT(0);
20599
0
    }
20600
0
    info->QuerySuccess = true;
20601
0
    info->DataType = data_type;
20602
0
}
20603
20604
static int StackToolFormatLevelInfo(ImGuiStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20605
0
{
20606
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20607
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20608
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20609
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20610
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20611
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20612
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20613
0
        return (*buf = 0);
20614
#ifdef IMGUI_ENABLE_TEST_ENGINE
20615
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20616
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20617
#endif
20618
0
    return ImFormatString(buf, buf_size, "???");
20619
0
}
20620
20621
// Stack Tool: Display UI
20622
void ImGui::ShowStackToolWindow(bool* p_open)
20623
0
{
20624
0
    ImGuiContext& g = *GImGui;
20625
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20626
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20627
0
    if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20628
0
    {
20629
0
        End();
20630
0
        return;
20631
0
    }
20632
20633
    // Display hovered/active status
20634
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20635
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20636
0
    const ImGuiID active_id = g.ActiveId;
20637
#ifdef IMGUI_ENABLE_TEST_ENGINE
20638
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20639
#else
20640
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20641
0
#endif
20642
0
    SameLine();
20643
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20644
20645
    // CTRL+C to copy path
20646
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20647
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20648
0
    SameLine();
20649
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20650
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20651
0
    {
20652
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20653
0
        char* p = g.TempBuffer.Data;
20654
0
        char* p_end = p + g.TempBuffer.Size;
20655
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20656
0
        {
20657
0
            *p++ = '/';
20658
0
            char level_desc[256];
20659
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20660
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20661
0
            {
20662
0
                if (level_desc[n] == '/')
20663
0
                    *p++ = '\\';
20664
0
                *p++ = level_desc[n];
20665
0
            }
20666
0
        }
20667
0
        *p = '\0';
20668
0
        SetClipboardText(g.TempBuffer.Data);
20669
0
    }
20670
20671
    // Display decorated stack
20672
0
    tool->LastActiveFrame = g.FrameCount;
20673
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20674
0
    {
20675
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20676
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20677
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20678
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
20679
0
        TableHeadersRow();
20680
0
        for (int n = 0; n < tool->Results.Size; n++)
20681
0
        {
20682
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
20683
0
            TableNextColumn();
20684
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
20685
0
            TableNextColumn();
20686
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
20687
0
            TextUnformatted(g.TempBuffer.Data);
20688
0
            TableNextColumn();
20689
0
            Text("0x%08X", info->ID);
20690
0
            if (n == tool->Results.Size - 1)
20691
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
20692
0
        }
20693
0
        EndTable();
20694
0
    }
20695
0
    End();
20696
0
}
20697
20698
#else
20699
20700
void ImGui::ShowMetricsWindow(bool*) {}
20701
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
20702
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
20703
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
20704
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
20705
void ImGui::DebugNodeFont(ImFont*) {}
20706
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
20707
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
20708
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
20709
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
20710
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
20711
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
20712
20713
void ImGui::DebugLog(const char*, ...) {}
20714
void ImGui::DebugLogV(const char*, va_list) {}
20715
void ImGui::ShowDebugLogWindow(bool*) {}
20716
void ImGui::ShowStackToolWindow(bool*) {}
20717
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
20718
void ImGui::UpdateDebugToolItemPicker() {}
20719
void ImGui::UpdateDebugToolStackQueries() {}
20720
20721
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
20722
20723
//-----------------------------------------------------------------------------
20724
20725
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
20726
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
20727
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
20728
#include "imgui_user.inl"
20729
#endif
20730
20731
//-----------------------------------------------------------------------------
20732
20733
#endif // #ifndef IMGUI_DISABLE